Implementing dynamic subtitles Cross-Browser.

I wanted to share a solution for dynamic subtitles with the html5 video tag as I’ve been through quite a journey to get it working cross browser on Chrome, Safari, Firefox, iOs & Android in mid 2015. (It seems to be working in Internet Explorer, too.)

I worked on a project where we had videos playing inside an html5 video div that were exchanged dynamically. So after a video finished, another one would get inserted into the video player by changing the source. Unfortunately the updated subtitle’s source wouldn’t reload on its own. The subtitle track needs to be deleted and re-added. Without that being enough all browsers behave differently in accepting the new subtitles and I couldn’t find any clear documentation for all browsers.

Firefox for example doesn’t seem to accept new subtitles if the “videocanplay” trigger hasn’t fired. Whereas Chrome does. – The „load“ event listener for tracks, doesn’t trigger in all browser somehow. – Chrome seems to hide subtitles the first time they’re inserted (I couldn’t find out why).

In the end I was brut-forcing to find the correct order in javascript and when I fixed one browser, at least one other one wasn’t working anymore.

Here’s a demo which is mostly similar to Ian Devlin’s solution with a fix for Chrome.

Please notify me if anyone finds a better solution or answers to the weird browser behaviors.

The Javascript Code:

videoplayer = document.getElementById("video");
source = document.querySelectorAll("#video > source");
var subtitleLink = "1";

videoplayer.addEventListener('play', function (e) {
	// remove old track and add new one
	kind = this.lastChild;
	track = document.createElement("track"); 

	//important to give type for chrome
	track.type = "vtt";
	track.src = "img/"+ subtitleLink +".vtt"; 
	track.kind = "subtitles"; 
	track.label = "English"; 
	track.srclang = "en";
	track.addEventListener("load", function() { 
   		video.mode = "showing"; 
    	video.textTracks[0].mode = "showing"; // For Firefox 


	 // Repeat "showing" the subtitles to make it work in Chrome 
	video.mode = "showing"; 
    video.textTracks[0].mode = "showing";

	//check current link and add the other one
	var currentLink = source[0].src.split("/").pop();

	if (currentLink == "1.mp4") {
		source[0].src = "img/2.mp4";
	 	source[1].src = "img/2.webm";
	 	subtitleLink = "2"
		source[0].src = "img/1.mp4";
	 	source[1].src = "img/1.webm";
	 	subtitleLink = "1"