javascript window.location in new tab
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();
})
Related videos on Youtube
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, 2020Comments
-
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 over 12 yearsDuplicate: stackoverflow.com/questions/427479/…
-
Khez over 12 yearsIs
window.location
a requirement? Or can other JS solutions be offered ? -
Muhammad Imran Tariq over 12 years@Khez: other JS can be offered.
-
Junaid khan almost 3 yearsyou can use the window.open()
-
-
pregmatch over 6 yearsbut what if your browsers has blocked settings on popup? this will not wok.
-
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 almost 2 yearsI 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.