document.querySelector('#ontime').onclick = function() {
setTimeout(() => {
window.open('https://www.google.com');
}, 1000);
};
在用户单击超时 <= 1000 毫秒(或 Promise.resolve().then(...)
)后使用 window.open 时,它不会被浏览器阻止.
如果您使用超时 > 1000 毫秒或 requestAnimationFrame
执行相同操作,弹出窗口将被阻止。
点击下面的链接可以获得 4 个案例的完整示例: https://jsfiddle.net/kouty79/rcwgbfxy/
有人知道为什么吗?是否有关于此的任何文档或 w3c 规范?
最佳答案
来自 HTML 5.2 :
An algorithm is allowed to show a popup if any of the following conditions is true:
…
event listener for a trusted event …
… queued by an algorithm that was allowed to show a popup, and the chain of such algorithms started within a user-agent defined timeframe.
onclick
是一个受信任的事件,但是 setTimeout
将它放在一个队列中(所以它没有被直接调用)所以弹出窗口必须在一定时间内出现。
那个时间由浏览器决定。
关于javascript - 为什么 window.open 在 setTimeout <= 1000ms 时不会被阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48788231/