How to open an URL in a new tab using 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.

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

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.

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.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

1 Response

  1. Maricruz says:

    Your way of explaining all in this paragraph is in fact nice, every one be capable of effortlessly understand it, Thanks
    a lot.

Leave a Reply

Your email address will not be published. Required fields are marked *