Open a URL in a new tab in JavaScript/jQuery
This post will discuss how to open a referenced resource of a link in a new tab in JavaScript and jQuery.
1. Using window’s open()
method
The idea is to use the window.open() method to open a resource into the browsing context. It accepts the URL of the resource and the target’s name, where the specified resource should be loaded (in a window or a tab).
Although the tab-capable browsers prefer opening new tabs to opening new windows, you can explicitly force this behavior by passing the _blank
target to the open()
method.
1 2 3 4 |
window.addEventListener("load", event => { var window = window.open("https://www.google.com/", "_blank"); window.focus(); }); |
Note that some browsers like Google Chrome will automatically block pop-ups from showing up on your screen. To prevent pop-up blockers, you can add window.open(url, "_blank")
in the onclick
event handler for a DOM object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!doctype html> <html lang="en"> <body> <button id="search">Search with Google</button> </body> <script> document.getElementById("search").onclick = function() { var window = window.open("https://www.google.com", "_blank"); window.focus(); }; </script> </html> |
2. Create hidden anchor tag
Another plausible way to open a referenced resource in a new tab is to dynamically create an anchor tag with the href
attribute set to the resource URL and the target
attribute set to _blank
for making it open in a new tab. After the object is created, don’t attach it to any DOM objects but trigger a click on it using JavaScript’s click()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!doctype html> <html lang="en"> <body> <button id="search">Search with Google</button> </body> <script> document.getElementById("search").onclick = function() { Object.assign(document.createElement("a"), { target: "_blank", href: "https://www.google.com" }).click(); }; </script> </html> |
With the jQuery library, you can create new anchor tag like:
1 2 3 4 5 6 7 8 |
$(document).ready(function() { $("#search").click(function() { $("<a>").prop({ target: "_blank", href: "https://www.google.com" })[0].click(); }); }); |
That’s all about opening a URL in a new tab in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)