Feature detect if user gesture is needed

你。 提交于 2020-01-22 12:15:10

问题


is there a way to detect if calling play() on a video element is allowed without a user gesture? On Android Chrome this warning is given:

Failed to execute 'play' on 'HTMLMediaElement': API can only be initiated by a user gesture.

So on Chrome Android a user gesture is required to start the playback of a video, while it isn't on desktop Chrome. Is there a way to detect which behavior I will get?

I want to have slightly different behavior in my app depending on if calling play programatically is allowed or not.

I have tried to use Modernizr.videoautoplay, but that checks if the autoplay property on the element, which is not the same thing. This gives false negatives for IE11 and Edge.

Edit: added an example. The video will start playing automatically in Chrome desktop and IE11 or Edge (with 3s delay) on windows 8 or 10. For Chrome@Android a user interaction is needed (clicking the button) and the error message can be seen in the console.


回答1:


The play method returns a promise which can be used to catch the error.

Not all browsers follow the specification so you will have to check if what is returned is a promise first.

var autoPlayAllowed = true;
var promise = document.createElement("video").play();
if(promise instanceof Promise) {
    promise.catch(function(error) {
        // Check if it is the right error
        if(error.name == "NotAllowedError") {
            autoPlayAllowed = false;
        } else {
            throw error;
        }
    }).then(function() {
        if(autoPlayAllowed) {
            // Allowed
        } else {
            // Not allowed
        }
    });
} else {
    // Unknown if allowed
}


来源:https://stackoverflow.com/questions/32653510/feature-detect-if-user-gesture-is-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!