-1

I am new in Javascript. I try to open 10 new tabs with the same link but when I run the code and click on the button it opens only one tab with this url. Please tell me how to do that in js.

Here is the code:

<button 
  onclick="virus()" 
  type="button" 
  name="button"
>Start your Magic!</button>

<script>
  function virus() {
    for(var i = 0; i < 10; i++) {
      window.open("https://www.w3schools.com/js/js_jquery_selectors.asp");
    }
  }
</script> 
biberman
  • 5,606
  • 4
  • 11
  • 35
Sanwar lal
  • 17
  • 6

3 Answers3

0

This is discussed extensively in this stackoverflow thread: Open multiple links in Chrome at once as new tabs

The long and short of it is that modern browsers don't seem to allow this.

Aaron Lavers
  • 967
  • 9
  • 31
0

First make sure you allow "Pop-ups and redirects" from chrome like the attached image.

Second try to wrap the code in a timeout like:

    for (var i = 0; i < 10; i++) {
        setTimeout(() => {
           window.open("https://www.w3schools.com/js/js_jquery_selectors.asp"  );
        }, 200);
    }

enter image description here

moustafa
  • 251
  • 2
  • 11
0

window.open() accepts a second parameter as windowName. So if there is no browsing context with a particular name, a new browsing context is created.

So since you haven't passed the second argument, all other window.open calls after the first one, will not create a new browsing context and won't open new windows/tabs.

So for a fix, you can try using the below code -

<button onclick="virus()" type="button" name="button"> Start your Magic!</button>
   <script>
       function virus(){
         for(var i=0;i<10;i++){
        window.open("https://www.w3schools.com/js/js_jquery_selectors.asp", i.toString());
         }
       }

I have passed a second argument as well to the window.open() which would help create a new browsing context every time the method is called.

jateen
  • 642
  • 3
  • 13