Detecting MP4 / Flash video support with Javascript

Playing video on the web is unfortunately a bit tricky. Different browsers support different formats. To support almost every browser you can use the code from Video for everybody. Disadvantage is you have to provide multiple videoformats: MP4 (H.264), WebM and Ogg (Theora).

Currently H.264 is the most viable option if you want to settle for a single format. Advantage is hardware support on many devices. Google has announced that H.264 support will be removed from Chrome in the future. This means the default fallback should be Flash! Unfortunately does Firefox not fallback to Flash if you only provide HTML5 video for MP4.

To make it easier you to load MP4 video, you can use the following Javascript code:


<script>
function supports_mp4() {
  try {
    return !!document.createElement('video').canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,'');
  } catch(e) {
    return false;
  }
}

function supports_flash() {
  var hasFlash = false;
  try {
    var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
    if(fo) hasFlash = true;
  }catch(e){
    var fm = navigator.mimeTypes["application/x-shockwave-flash"];
    if( fm && fm.enabledPlugin ) hasFlash = true;
  }
  return hasFlash;
}

if( supports_mp4() ) {
  // Use HTML5 Video
} else if( supports_flash() ) {
  // Use Flash
} else {
  // Downloadlink or something ...
}
</script>