0

我正在处理一些通过单击按钮调用的 js 代码,启动一些可能导致需要打开的窗口的异步操作。为了防止弹出窗口阻止程序,我需要确保 window.open 调用是通过单击按钮完成的。

我一直在玩 setTimeout 和 setInterval 以每 100 毫秒左右检查一次异步操作是否完成,并在需要时打开窗口。

我通过 setInterval n 次调用函数在我的jsfiddle中模拟了这一点,第 n 次调用调用 window.open。

Javascript:

// in chrome this only works with n = 1, otherwise the open-call is blocked
var n = 2
var timer

function tst1() {
    console.log('tst1.start ' + n)
    if (--n == 0) {
        clearInterval(timer)
        window.open('http://google.com/', '_blank')
    }
    console.log('tst1.done')
}

function tst() {
    timer = setInterval(tst1, 1000)
}

html:

<button onclick="tst()">Click me</button>

问题是,这只适用于第一次(在 js 代码的第一行 n=1),当 n 设置为 2 或更大时,它在 Firefox 中有效,但在 chrome 中无效。

知道如何在所有现代浏览器中使其工作吗?

4

0 回答 0