How to open an URL in a new tab using JavaScript
Today, we’ll explain to you how to open an URL in a new tab using JavaScript.
In the HTML, using the target="_blank"
attribute in anchor tag (<a>
), we can easily open the URL in a new tab or window.
1 | <a href="https://www.cluemediator.com/" target="_blank" rel="noopener noreferrer">Visit Clue Mediator</a> |
However, sometimes you need to open an URL in a new tab using JavaScript. So here we will show you the different ways to do this task.
Different ways to open an URL in a new tab
Let’s start with an example for better understanding.
1. window.open() method
The window.open() method open a new browser window or a new tab based on the browser settings and the given parameters.
Syntax
1 | const window = window.open(url, windowName, features); |
The windowName
specifies the target attribute and supports the following.
- _blank – The URL will open in a new window or tab. This is the default value.
- _parent – The URL will load into the parent window.
- _self – The URL replaces the current web page.
- _top – The URL replaces any framesets that may be loaded.
- name – The name of the window.
Example
Here, we will show you that the URL opens in a new tab when the button is clicked.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!DOCTYPE html> <html> <head> <title>Open an URL in new tab using JavaScript</title> </head> <body> <button id="clickBtn">Click Here</button> <script type="text/javascript"> const button = document.querySelector('#clickBtn'); // add click event listener button.addEventListener('click', () => { // open a URL in new tab window.open('https://www.cluemediator.com/', '_blank'); }); </script> </body> </html> |
2. Create hidden anchor tag
In another way, it creates a virtual element, gives it target="_blank"
so it opens in a new tab.
After the object is created, don’t add it in the DOM but trigger a click event using the JavaScript’s click()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!DOCTYPE html> <html> <head> <title>Open an URL in new tab using JavaScript</title> </head> <body> <button id="clickBtn">Click Here</button> <script> const button = document.querySelector('#clickBtn'); // add click event listener button.addEventListener('click', () => { Object.assign(document.createElement("a"), { target: "_blank", href: "https://www.cluemediator.com/" }).click(); }); </script> </body> </html> |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂
Your way of explaining all in this paragraph is in fact nice, every one be capable of effortlessly understand it, Thanks
a lot.