功能检测是否需要用户手势 [英] Feature detect if user gesture is needed

查看:103
本文介绍了功能检测是否需要用户手势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检测是否允许在没有用户手势的情况下在视频元素上调用 play()
在Android Chrome上发出此警告:

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:

无法在'HTMLMediaElement'上执行'play':API只能由用户手势。

因此,在Chrome Android上,需要用户手势才能开始播放视频,而不是在桌面上铬。
有没有办法检测我会得到哪种行为?

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?

我想在我的应用中略有不同的行为,具体取决于是否允许以编程方式调用play或者不是。

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

我试图使用 Modernizr.videoautoplay ,但检查元素上的autoplay 属性,这不是一回事。这给IE11和Edge带来漏报。

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.

编辑:添加一个例子。视频将在Windows桌面和IE11或Edge上自动播放(在Windows 8或10上有3秒延迟)。对于Chrome @ Android,需要用户交互(单击按钮),并且可以在控制台中看到错误消息。 / p>

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.

推荐答案

play方法返回一个可用于捕获错误的promise。

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
}

这篇关于功能检测是否需要用户手势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆