How do I detect if the HTML5 autoplay attribute is supported?

前端 未结 9 739
遇见更好的自我
遇见更好的自我 2020-12-05 05:04

How do I best detect whether a browser\'s HTML5 video element supports autoplay?

On current iOS Safari, for example, autoplay is disabled.

Update:

9条回答
  •  北海茫月
    2020-12-05 05:21

    Modernizr autoplay test has some reliability issues, as pointed here: https://github.com/Modernizr/Modernizr/issues/1095

    You can detect video autoplay support by checking if the paused status of a video element changes after it programmatically plays. This alone can return false negatives in some mobile browsers, so a Promise check should be added in order to cover these.

    This method works in all major browsers (desktop and mobile), except for Android <= 4.0 and Windows Phone, where it returns a false negative.

    Here is the detect function:

    var supports_video_autoplay = function(callback) {
    
      if (typeof callback !== "function") return false;
    
      var v = document.createElement("video");
      v.paused = true;
      var p = "play" in v && v.play();
    
      callback(!v.paused || ("Promise" in window && p instanceof Promise));
    
    };
    

    Usage:

    supports_video_autoplay(function(supported) {
      if (supported) {
        // video autoplay supported!
      } else {
        // no video autoplay support :(
      }
    });
    

    Live test: https://codepen.io/paulorely/pen/QveEGy

提交回复
热议问题