Open In App

How to Open URL in New Tab using JavaScript?

Last Updated : 13 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

HTML anchor tag is used to open URLs in a new tab using the target=”_blank” attribute. In JavaScript, we have an inbuilt method window.open() which is used to open a new browser window or new tab depending on the browser settings.

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: In this example, we create a button that, when clicked, uses JavaScript (window.open) to open “geeksforgeeks.org” in a new browser tab, maintaining the current page’s context.

HTML
<html>

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

<body>

    <p> Click the button to open
        <b> geeksforgeeks.org </b>
        in new tab
    </p>


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

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

</body>

</html>

Output:

new-tab

Important Notes:

  • The return value of window.open() is a reference to the newly created window or tab. It returns null if it fails to open the new tab.
  • Avoid adding a third parameter to the window.open() method because it could result in a new window instead of a tab.

Supported Browsers:

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



Next Article
Article Tags :

Similar Reads