0

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

Rob Gansevles
  • 143
  • 1
  • 10
  • http://stackoverflow.com/a/4989867/4332533 – Freez Feb 16 '15 at 23:09
  • possible duplicate of [opening new windows after specifc interval of time using window.open()](http://stackoverflow.com/questions/4989537/opening-new-windows-after-specifc-interval-of-time-using-window-open) – Andreas Louv Feb 16 '15 at 23:10
  • 2
    I'm literally going to report this as a Firefox bug. – Pointy Feb 16 '15 at 23:11
  • Not really sure what you're doing, but if you're going to open a new window you should do it as the immediate cause of a user action. Websites that just "randomly" (from the user's point of view) open windows are generally not websites that the user will return to later. – Jhecht Feb 16 '15 at 23:16
  • The new window is supposed to open from the button-onclick, so it is not at random. Problem is that I have to wait for an asynchronous action to complete (a message is sent over a websocket and a response message may require a window.open). I also wonder why it does work with n=1, the first call to tst1 is done when the button on-click has already returned so some state from the button-click-threat is kept. But only for the first, why not for the second? – Rob Gansevles Feb 17 '15 at 07:11

0 Answers0