当用户与页面交互时是否有一个事件可以检测?

问题描述 投票:0回答:3

我试图在用户与页面交互后立即自动播放视频。如果我之前播放视频,我显然会收到安全错误:

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

这是公平的,我发现了这个错误,现在想要注册一个事件以便在用户与页面交互后立即重试播放。

=> 有这样的活动吗?

我尝试在 mouseover / mousemove / touchmove / click / focus /visibilitychanged 上注册事件,但它不是最佳的,并且经过一些测试后不是很可靠......

javascript html events video autoplay
3个回答
7
投票
我知道这是一个老问题,但对于任何处理此问题的人来说,

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);
    

0
投票
截至 2023 年,有一个新的

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


-2
投票
注册多个事件并等待一个事件起作用。

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); } } }); });

© www.soinside.com 2019 - 2024. All rights reserved.