Calling window.open() multiple times fails after the first time

Viewed 2560

I have a script that loops through multiple urls and opens them in a new tab. It used to work but now only opens the first one. There's even a w3schools test editor that supposedly opens multiple windows, and it also fails after the first one:

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_open6

However, if I step through in debug mode and reset the focus to to original tab each time, it does open each window. So my question is, how do I open multiple windows(tabs) but keep the focus on my window with the original script? It used to do it that way, but now, as soon as a new tab is added, it gets the focus, and the script stops opening windows. Here's the full w3schools failing script:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to open multiple windows.</p>

<button onclick="myFunction()">Open Windows</button>

<script>
function myFunction() {
    window.open("http://www.google.com/");
    window.open("https://www.w3schools.com/");
}
</script>

</body>
</html>
3 Answers

I think as @Daniel Sharp said, there is a security feature in chrome. It works fine in FF and IE.

It works if I follow below steps:

  1. Click Open Windows (A new window will open)
  2. Click on inital browser tab
  3. Click somewhere on the page (Except Open Windows button)
  4. Click on Open Windows again (IT works this time - two windows are open)

As noted in another answer and the comments, it is a security feature.

It is worth adding, however, that you can disable it (on a per-site basis): simply click the small "popup blocker" icon at the right end of the address bar and enable popups from the current site.

Afterwards, feel free to shoot as many window.open's as you need.

The window name should be unique. Otherwise, the same page will refresh

function myFunction() {
    window.open("https://www.google.com/","_google","height=200,width=150");
    window.open("https://www.w3schools.com/","_w3schools","height=200,width=150");
}
Related