javascript window.location in new tab

295,296

Solution 1

I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open and hoping that the user has their browser set to open new windows in new tabs.

Solution 2

window.open('https://support.wwf.org.uk', '_blank');

The second parameter is what makes it open in a new window. Don't forget to read Jakob Nielsen's informative article :)

Solution 3

You can even use

window.open('https://support.wwf.org.uk', "_blank") || window.location.replace('https://support.wwf.org.uk');

This will open it on the same tab if the pop-up is blocked.

Solution 4

This works for me on Chrome 53. Haven't tested anywhere else:

function navigate(href, newTab) {
   var a = document.createElement('a');
   a.href = href;
   if (newTab) {
      a.setAttribute('target', '_blank');
   }
   a.click();
}

Solution 5

with jQuery its even easier and works on Chrome as well

$('#your-button').on('click', function(){
       $('<a href="https://www.some-page.com" target="blank"></a>')[0].click();    
})
Share:
295,296

Related videos on Youtube

Muhammad Imran Tariq
Author by

Muhammad Imran Tariq

I am a passionate Senior Software Engineer. Majorly work in Java and BigData. I completed my masters degree in computer science and since then I developed various business application on different domains including financial systems, digitalsignage, security etc. I am also a good web developer and worked on different websites such as blogs, shopping carts. I have good understanding of programming languages and software development pros and cons.

Updated on October 25, 2020

Comments

  • Muhammad Imran Tariq
    Muhammad Imran Tariq over 3 years

    I am diverting user to some url through window.location but this url opens in the same tab in browser. I want it to be open in new tab. Can I do so with window.location? Is there another way to do this action?

    • Samich
      Samich over 12 years
    • Khez
      Khez over 12 years
      Is window.location a requirement? Or can other JS solutions be offered ?
    • Muhammad Imran Tariq
      Muhammad Imran Tariq over 12 years
      @Khez: other JS can be offered.
    • Junaid khan
      Junaid khan almost 3 years
      you can use the window.open()
  • pregmatch
    pregmatch over 6 years
    but what if your browsers has blocked settings on popup? this will not wok.
  • TARKUS
    TARKUS over 4 years
    @Alex meh...not really the "right" answer. Trying this in Firefox, where I prevent pop-up windows, this code fails.
  • Troy Watt
    Troy Watt almost 2 years
    I would avoid this solution because window.open in some cases could return null (but still open a new window as expected) while also triggering location.replace on the current tab resulting in two open tabs with the new url. Using a try/catch described in this answer may be a better solution stackoverflow.com/a/27725432/811533.