Sometimes, we want to detect supported video formats for the HTML5 video tag with JavaScript.
In this article, we’ll look at how to detect supported video formats for the HTML5 video tag with JavaScript.
How to detect supported video formats for the HTML5 video tag with JavaScript?
To detect supported video formats for the HTML5 video tag with JavaScript, we can use the video element’s canPlayType
method.
For instance, we write:
<video></video>
to add a video element.
Then we write:
const testEl = document.querySelector('video')
const mpeg4 = "" !== testEl.canPlayType('video/mp4; codecs="mp4v.20.8"');
const h264 = "" !== (testEl.canPlayType('video/mp4; codecs="avc1.42E01E"') ||
testEl.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'));
const ogg = "" !== testEl.canPlayType('video/ogg; codecs="theora"');
const webm = "" !== testEl.canPlayType('video/webm; codecs="vp8, vorbis"');
console.log(mpeg4)
console.log(h264)
console.log(ogg)
console.log(webm)
to select the video element with querySelector
.
Then we call testEl.canPlayType
with various format strings to check if various video formats can be played.
If they can be played, then canPlayType
should return something other than an empty string.
Conclusion
To detect supported video formats for the HTML5 video tag with JavaScript, we can use the video element’s canPlayType
method.