JavaScript program to open one url in a new tab

Open one URL in a new tab :

The anchor tag is used in HTML to open one new link in a new page. You can use this tag if you have a static URL. But, sometimes, we may need to do it dynamically as if the user clicks on a button, we will open one link in a new tab. We need JavaScript for that. JavaScript provides one method called window.open() that can be used to open a link in a new browser tab.

In this post, I will show you how to open one URL in a new tab using JavaScript.

How to open a URL in a new tab in ‘a’ attribute :

The below __ target attribute will open the URL in a new tab on click :

<a href="https://www.codevscolor.com" target="_blank">Click here</a>

Using JavaScript :

We will use window.open() to replicate the exact behavior. The first parameter should be the URL we are opening and the second parameter is _blank.

<!DOCTYPE html>
<html>
<body>

<button id="button" type="button">Click Here</button>

</body>
<script>
function openUrl(){
  window.open('https://www.codevscolor.com', '_blank');
}

document.getElementById("button").onclick = function() {openUrl()};

</script>
</html>

In this example, if you click on the button, the javascript will invoke the openUrl method that will open the URL in a new tab.

javascript open link in new tab