How To Enable Cors For Html5 Video Loading Vtt File?
My Need html5 video element loads both a video and a vtt file saved in a different domain. The problem vtt is not loaded and error Text track from origin has been blocked from load
Solution 1:
Hopefully this helps the next person to stumble upon this SO question. I discovered that IE (10 and 11) does not support loading a cross-origin VTT file for a <track>
, even if CORS is enabled. In order to add IE support for captions, I had to use a script like the one below.
This script downloads each VTT file via AJAX, creates a blob URL, and replaces each <track>
src with its respective blob URL.
window.addEventListener("load", function() {
if (window.navigator.userAgent.indexOf("MSIE ") < 0 && window.navigator.userAgent.indexOf("Trident/") < 0) {
// Not IE, do nothing.return;
}
var tracks = document.querySelectorAll("track")
for (var i = 0; i < tracks.length; i++) {
loadTrackWithAjax(tracks[i]);
}
});
functionloadTrackWithAjax(track) {
var xhttp = newXMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 && this.responseText) {
// If VTT fetch succeeded, replace the src with a BLOB URL.var blob = newBlob([this.responseText], { type: 'text/vtt' });
track.setAttribute("src", URL.createObjectURL(blob));
}
};
xhttp.open("GET", track.src, true);
xhttp.send();
}
<videocontrolspreloadwidth="600"height="337.5"autoplaycrossorigin="anonymous"><sourcesrc="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4"type="video/mp4"></source><trackkind="captions"label="English"srclang="en"src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt"default></video>
Solution 2:
I can confirm that the crossorigin=anonymous
attribute on the video
element does indeed load the text track as expected.
Give this code a shot:
<videoid="myvideo"controlspreload="auto"width="640"height="264"autoplaycrossorigin="anonymous"><sourcesrc=http://video.dublearn.net/-KqIgE-3roMSBbiHUmLI/video.mp4type="video/mp4"></source><trackkind="captions"label="English"srclang="en"src=http://video.dublearn.net/-KqIgE-3roMSBbiHUmLI/video.vttdefault></video>
Finally, remember, you must use a web server to serve this HTML snipped - this cannot be done locally (ie. file//
).
If you're familiar with node
- install http-server
, run with --cors
and use ngrok.
Post a Comment for "How To Enable Cors For Html5 Video Loading Vtt File?"