Clue Mediator

How to open an URL in a new tab using JavaScript

šŸ“…January 27, 2021
šŸ—JavaScript

Today, weā€™ll explain to you how to open an URL in a new tab using JavaScript.

In the HTML, using the `target="_blank"` attribute in anchor tag (`<a>`), we can easily open the URL in a new tab or window.

<a href="https://www.cluemediator.com/" target="_blank" rel="noopener noreferrer">Visit Clue Mediator</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

  1. window.open() method
  2. Create hidden anchor tag

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.




    <title>Open an URL in new tab using JavaScript</title>


<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://www.cluemediator.com/', '_blank');
});
</script>

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.




    <title>Open an URL in new tab using JavaScript</title>


    <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://www.cluemediator.com/"
    }).click();
});
</script>

Thatā€™s it for today.
Thank you for reading. Happy Coding..!! šŸ™‚