Open URL in New Tab using JavaScript
Today, we’ll explain to you how to open an URL in a new tab using JavaScript.
We may quickly open the URL in a new tab or window in HTML by using the target="_blank"
property in the anchor tag (<a />
).
<a href="https://codepremix.com/" target="_blank" rel="noopener noreferrer">Visit Code Premix</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
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.
<html>
<head>
<title>Open 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://codepremix.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.
<html>
<head>
<title>Open 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://codepremix.com/"
}).click();
});
</script>
</body>
</html>
That’s it for today.
Thank you for reading. Happy Coding..!!