我试图在用户与页面交互后立即自动播放视频。如果我之前播放视频,我显然会收到安全错误:
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
这是公平的,我发现了这个错误,现在想要注册一个事件以便在用户与页面交互后立即重试播放。
=> 有这样的活动吗?我尝试在 mouseover / mousemove / touchmove / click / focus /visibilitychanged 上注册事件,但它不是最佳的,并且经过一些测试后不是很可靠......
play()
都会返回一个承诺。所以你可以做类似下面代码的事情。此代码将尝试每 5 秒触发一次
play()
函数,直到成功为止,然后它将清除间隔。不确定它是否也适用于视频,但我认为是这样。
const tryToPlay = setInterval(() => {
const audio = new Audio(theAudioFile);
audio.play()
.then(() => {
clearInterval(tryToPlay);
})
.catch(error => {
console.info('User has not interacted with document yet.');
});
}, 5000);
userActivation
属性用于检查是否执行了用户手势。这是一个例子:
let autoPlayAttempt = setInterval(() => {
const videoElement = document.getElementById("video");
if (navigator.userActivation.hasBeenActive) {
videoElement.play();
clearInterval(autoPlayAttempt);
}
}, 1000);
来源:https://developer.mozilla.org/en-US/docs/Web/API/UserActivation
let isPlaying = false;
["click", "mousemove", "mouseover", "mousemove", "touchmove", "focus"].forEach((eventName)=>{
window.addEventListener(eventName, ()=>{
if(!isPlaying){
try{
//play video here
console.log("Video is playing");
isPlaying = true;
}catch(e){
console.warn(e.message);
}
}
});
});