Open two tabs with one link

Hey again!

I am trying to get two tabs to open with one link click this is what I got so far but isn’t working:

    let clickMe = document.querySelector(".header-right a");
    clickMe.addEventListener("click", (e) => {
        e.preventDefault();
        window.open('https://bbc.co.uk', '_blank');
        window.open('https://news.sky.com', '_blank');
    });

I was reading this was not possible? Does anyone know what I can do here?
Cheers!!

Can anyone help with this please?

Every window opened must be initiated by a user action such as a click. One action, one window. Otherwise, a script could open dozens or hundreds of spam popup windows on one click. Firefox will show a “popup blocked” warning that will allow the second window to be opened if the user allows it, but Chrome will simply block it silently. There really isn’t any way to get what you’re after: two windows will require two clicks.

1 Like

Unfortunately, the closest you can get to what you want is add the first link as the href attribute of your anchor element and then:

    let clickMe = document.querySelector(".header-right a");

    clickMe.addEventListener("click", (e) => {
        window.open('https://news.sky.com', 'sky');
    });

This is not exactly what you wanted, but does allow both sites to be shown.

1 Like

Thanks Randell but I am struggling to see how this opens both?! Thanks!

When you click on the actual link, the bbc site loads on the page and then the JavaScript opens the other page. Both pages are accessible in tabs.

So would I need to do it like this:

    let clickMe = document.querySelector(".header-right a");
    clickMe.addEventListener("click", (e) => {
        e.preventDefault();
        window.open('https://bbc.co.uk', '_blank');
       //Like this??          
      location.href = "https://news.sky.com";
    });

You could to do or you could do what I said above (using my code) and use the BBC url as the anchor tags attribute value.

<a href="https://bbc.co.uk">Click me</a>
1 Like

That is odd as I already have an anchor in the link and it doesn’t fire how you are saying. Let me have a play with it and see if I can get it to work
cheers :slight_smile:

Are you doing this locally or using Codepen?

I am working locally on a project but can use JS fiddle for example if you like?

The following works for me locally using Chrome.

<!DOCTYPE html>
<html>
<body>
  <a href="https://bbc.co.uk">Click me</a>
  <script>
    let clickMe = document.querySelector("a");
    clickMe.addEventListener("click", (e) => {
      window.open('https://news.sky.com', 'sky');
    });
  </script>
</body>
</html>
2 Likes

Thank you for this. Do you know of another way of opening tabs / links in JS apart from these two

  • Window.open

  • location.href

Are there more ways? I’ve got it working now by the way, just interested - cheers :slight_smile: