Rahul Rahul - 1 year ago 101
Javascript Question

How to add subtitle in video player using online link?

How to add subtitle in video player using online link? Even when we use local subtitle file (.vtt file) subtitle is working but when we change the source of subtitle from local file to online link then no subtitle displayed, we are using html5 and javascript to add subtitle.


<video id="vid1" height="720" width="1280">
<track id="text1" label="English" kind="subtitles" src="" srclang="en">


var text = document.getElementById("text1");
var video = document.getElementById("vid1");
video.setAttribute("src","online video URL link here...");// video is playing fine.
text.setAttribute("src", "../../assets/static/creed.vtt"); // this is a local file and this one is working fine.
text.setAttribute("src", ""); // This file is stored in server, and we are using link to fetch the file but it is not working.
// one more online link is not working
text.setAttribute("src", " http://devcache.ff.msf.ioko.com/Test/Movies/2016/6/28/SDFEATUREMOVIE/Creed%20ENG.VTT"); // This file is also not working
video.textTracks[0].mode = 'showing'; // only local stored file is working others are not working.

Answer Source

This is because CORS limitation. Major browsers block requests from other domains to prevent attacks. Unless the requested server allows cross domain sharing.

So first try adding crossorigin="anonymous" to video tag

<video id="vid1" height="720" width="1280" crossorigin="anonymous">
    <track id="text1" label="English" kind="subtitles" src="" srclang="en">

if the above code didn't work, there is no way to load the subtitle from that server, unless you are the owner and in that case, you need to allow access to others by sending Access-Control-Allow-Origin header in response.

if that not possible you have to upload the subtitles locally to your server.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download