Search code examples
javascriptbrowserhttp-live-streaming

How can I precisely detect HLS support on different browsers and different OS?


According to this answer, to test the browser's capabilities to play HLS video, the MIME application/x-mpegURL can be used. But the problem with this approach is that it is returning maybe for iPhone (actually supports HLS) as well as for Firefox for Android (which doesn't support). Though this works well by returning an empty string in case of desktop browsers such as Chrome and Firefox.

Is there any precise way to check for HLS support in a browser?

HTML5test.com could able to predict the HLS support precisely as Yes or No. How is this functioning?


Solution

  • JavaScript version

    function supportsHLS() {
      var video = document.createElement('video');
      return Boolean(video.canPlayType('application/vnd.apple.mpegURL') || video.canPlayType('audio/mpegurl'))
    }
    

    Then use it as:

    if (supportsHLS()) {
      myVideoElement.src = 'your-hls-url.m3u8';
    } else {
      myVideoElement.src = 'your-plain-video-url.mp4';
    }
    

    HTML-only version (preferred)

    Let the browser pick the first source it supports. This is safer.

    <video>
        <source src="your-hls-url.m3u8" type="application/vnd.apple.mpegurl">
        <source src="your-plain-video-url.mp4" type="video/mp4">
    </video>