0

The window onload event was not triggering while a new tab being opened. The following is the sample code for doing the same. Here a list of URLs is being tried to open in separate same tab one after another, as the onload event is not being triggered, the recursive calls are not being happening.

var urls = ['https://stackoverflow.com/q/4907843', 'https://stackoverflow.com/q/19851782', 'https://stackoverflow.com/q/726761'];

function opennewtab(i) {
  var w = window.open(urls[i], 'so', '');
  if (w) {
    w.onload = function() {
      opennewtab(i + 1);
    }
  }
};

opennewtab(0);

All are in same domain. Please paste the code snippet in the browser developer tools in same page here.

Justin John
  • 9,223
  • 14
  • 70
  • 129
  • 1
    You can't set variables in a page from a different domain. – Barmar Aug 27 '19 at 17:19
  • @Barmar It's the same domain. – Justin John Aug 27 '19 at 17:19
  • Also, when you open those pages, they don't load your JavaScript, so the function `opennewtab()` doesn't exist there. – Barmar Aug 27 '19 at 17:20
  • The original page is in the `stackoverflow.com` domain? – Barmar Aug 27 '19 at 17:20
  • @Barmar Yes, Please try this in very same page here in browser developer tools. – Justin John Aug 27 '19 at 17:21
  • I guess, this might be because onload event is triggered before actual code event listening code is being executed. – Justin John Aug 27 '19 at 17:30
  • That could be. JavaScript is single-thread in one window, but each window has its own thread. – Barmar Aug 27 '19 at 17:31
  • 1
    You could try opening the window to a blank URL, add the `onload` property, then redirect the window to the target URL, which should trigger a second event. – Barmar Aug 27 '19 at 17:32
  • 1
    Wow what a mess... I spent about two hours on this and still didn't succeed. Here are a few points that may help someone with more time than myself. `open(url, "name")` always returns the same Window instance. However, the Events you attach to it will get removed at each `unload` event. Given this, I made [this](https://plnkr.co/edit/hGOpTGovhrhWXZ70CAXz?p=preview), which actually works... if you are not focused on that window! That is, you need to come back to the main window for it to work... That's a very weird behavior, but given both Chrome and FF do the same, I'd assume it's standard... – Kaiido Aug 28 '19 at 07:23

1 Answers1

0

why not use the promises? I have not tested, but it should look something like this:

const urls = 
    [ 'https://stackoverflow.com/q/4907843'
    , 'https://stackoverflow.com/q/19851782'
    , 'https://stackoverflow.com/q/726761'
    ] 

function Load_URL(url) {
  return new Promise(res=>{
    let w = window.open(url, 'so', '')
    w.addEventListener('load', res)
  }) 
}

for (let url_x of urls) await Load_URL(url_x)
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40