While we are working in HTML, we can put the “_blank” value to the target attribute and the URL link will be opened in a new tab. But how to achieve this job when you are using JavaScript. We will talk about how to open a URL in a new tab using JavaScript in this write-up.
Opening URL in a new tab using HTML
A hyperlink to another page is created with the anchor element <a> in HTML. We use the href property to give the URL of the page we want the user to prompt to and the “_blank” value to the target attribute of the tag for opening the link in a new tab.
A traditional method to get this job done is as follows:
Now, if you click on the link “Linuxhint Website”, the “linuxhint.com” will open up in the new tab.
This was a traditional way to open a link in a new tab.
Now we are going to have a look at how we can achieve this by using JavaScript
Opening URL in a new tab using JavaScript
To open a URL in a new tab using JavaScript, the window.open() method can be utilized.
The technique is pretty simple. We just have to pass two arguments to the window.open() method. One is the URL of the web page. The second argument is the same as the target attribute in the anchor tag <a> in which we specify where we want to open up the URL e.g. “_blank”.
Let’s think of an example, in which we want to open the “linuxhint.com” website in a new tab with the click of the button.
After creating a button in HTML, we have called a function named “newTab()”.
Let’s define it in our JavaScript code where we will use the window.open() method and provide it the URL of the “linuxhint.com” website and “_blank” value for opening the website in a new tab.
JS
window.open("https://linuxhint.com", "_blank");
}
Let’s execute the code and see the results.
When we click on the button “Click” it opens the “linuxhint.com” in a new browser tab.
Additional Methods
Here are some additional properties that you can attach while opening a URL:
- _blank: The URL is opened in a new tab.
- _parent: The parent frame is loaded with the URL.
- _self: The current page is replaced when this property is called
- _top: Any loaded framesets are replaced by the URL name – the widow’s name.
Conclusion
For opening the URL in the new tab, you have to put the _blank value to the target attribute of the anchor <a> tag in the HTML. You can also select the anchor tag using a JavaScript selector and add the target attribute with _blank value. In this post, we have seen how we can use the window.open() property at the onClick event of the button for opening the URL in the new tab programmatically through JavaScript.