0

I have a chrome extension and I want the user to navigate to some page on button click, I get the URL from the server so I need to wait for the promise to resolve to know where to redirect the user to. I tried doing it in the then section of the promise but realized it doesn't work because window open works only when triggered on the main thread as a result of user action (as explained here).

One solution I came up with is using setInterval and for some reason it works. I don't know why and would love to understand better, maybe it's flaky and I shouldn't use it.

My code looks somewhat like this

const onClick = () => {
  const urls: string[] = []
  somePromise.then((url) => {
    urls[0] = url
  })

  setInterval(() => {
    const possibleURL = urls[0];
    if (possibleURL) {
      window.open(possibleURL, '_top')
    }
  }, 500)
}

Thanks in advance

S Ro
  • 33
  • 7
  • you dont need a setInterval, just place the code which is inside it, in the then, under `urls[0] = url` – Lawrence Cherone Apr 19 '23 at 13:03
  • But it won't work, I can't window.open outside of user interaction because the browser will block it – S Ro Apr 19 '23 at 13:08
  • np, in linked question it answer your question: *reason it works*, so this is a duplicate question, it seems it would also work without the setInterval, if you assign window.open to a var and then only set its location in the then callback – Lawrence Cherone Apr 19 '23 at 13:51
  • But I don't want to open a window and then change it's location, I want to present a loader and only when I get the url to open the new tab. I guess this is the difference and that's why it's not a duplication – S Ro Apr 20 '23 at 15:59

0 Answers0