JavaScript: Programmatically open a URL in a new tab/window

Updated: March 31, 2023 By: Goodman Post a comment

What is the point?

Open a URL in a new tab

In JavaScript, you can programmatically open a URL in a tab by using the window.open() method. The URL needs to be passed as the first argument, and _blank needs to be passed as the second argument, as shown below:

const openInNewTab = (url) => {
  window.open(url, '_blank').focus();
}

The function openInNewTab above will launch the given URL in a new tab and focus on it. You can call it from a button click event handler, or any other event you want.

Open a URL in a new window

In case you want to open a URL in a new window (not a new tab) by using JavaScript, you can use the window.open() method with some window features as the third argument. The window features are a comma-separated list of items that specify the appearance and behavior of the new window, such as its size, position, scrollbars, status bar, etc. Here’s the general syntax:

const openInNewWindow = (url) => {
  window.open(url, '_blank', 'height=400,width=600,left=10,top=10,scrollbars=yes,status=yes');
}

There is an important thing you should be aware of is that some browsers may ignore or override some of your settings for security or usability reasons. Also, note that some browsers may block pop-ups by default.

Complete example

Preview

The sample webpage we’re going to make contains 2 buttons. When the button on the left side gets clicked, a URL will be opened in a new tab. When the other button is clicked, the URL will be opened in a new window.

Here’s the demo:

The code

The full source code that creates the demo above:

<html>

<head>
  <title>Sling Academy</title>
  <script>
    // Open in new tab
    const openInNewTab = () => {
      const url = 'https://www.example.com';
      window.open(url, '_blank').focus();
    }

    // Open in new window
    const openInNewWindow = () => {
      const url = 'https://www.example.com';
      window.open(url, '_blank', 'height=400,width=600,left=300,top=50');
    }
  </script>
</head>

<body>
  <button onclick="openInNewTab()">Open In New Tab</button>
  <button onclick="openInNewWindow()">Open In New Window</button>

</body>

</html>

You can copy and paste this code into an HTML file and then open it with your favorite web browser. Enjoy!