How to Open URL in New Tab using JavaScript ?

To open a URL in a new tab using JavaScript, utilize the window.open() method, providing the URL as the first argument and “_blank” as the second argument to specify opening in a new tab. This triggers the browser to open the URL in a new tab.

Using window.open() method

  • To open a new tab, we have to use _blank in the second parameter of the window.open() method.
  • The return value of window.open() is a reference to the newly created window or tab or null if it failed.
  • Do not add a third parameter to it as it will result in the opening of a new window rather than a tab

Syntax:

window.open(URL, '_blank');

Example 1: In this example, we have used the above-explained approach.

HTML
<html>

<head>
    <title>Open URL in New Tab </title>
</head>

<body>


    <p> Click the button to open
        <b> w3wiki.net </b>
        in new tab
    </p>


    <button onclick="NewTab()">
        Open w3wiki
    </button>

    <script>
        function NewTab() {
            window.open(
"https://www.w3wiki.net", "_blank");
        }
    </script>

</body>

</html>

Output:

Using the anchor element (HTML DOM

Using the anchor element (HTML DOM) involves creating an ‘a’ element dynamically, setting its href attribute to the desired URL, and its target attribute to “_blank”. Finally, triggering a click event on the element opens the URL in a new tab.

Example: In this example we creates a button to open “w3wiki.net” in a new tab. Upon click, it dynamically generates an ‘a’ element with the desired URL and “_blank” target, triggering a click event to open the link in a new tab.

HTML
<html>

<head>
    <title>Open URL in New Tab </title>
</head>

<body>


    <p> Click the button to open
        <b> w3wiki.net </b>
        in new tab
    </p>


    <button onclick="NewTab()">
        Open w3wiki
    </button>

    <script>
        function NewTab() {
            let newTab = document.createElement('a');
            newTab.href = "https://www.w3wiki.net";
            newTab.target = "_blank";
            newTab.click();
        }
    </script>

</body>

</html>

Output:

Supported Browsers

The browsers are supported by the window.open() method are listed below: