I am working on some js code that is called from a button click, starts some asynchronous action that may result in a window that needs to be opened. To prevent popup-blockers I need to make sure the window.open call is done from the button-click.
I have been playing around with setTimeout and setInterval to check every 100ms or so if the async action is done and open the window if needed.
I simulate this in my jsfiddle by calling a function via setInterval n times, the n-th call calls 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>
Problem is, this only works first time (n=1 on first line in js code), when n is set to 2 or more, it works in Firefox but not in chrome.
Any idea how to make this work in all modern browsers?
Rob