DEV Community

Cover image for How to open a new tab without getting blocked by the browser using JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to open a new tab without getting blocked by the browser using JavaScript?

Originally posted here!

To open a new tab without getting blocked by the browser, you need to use the window.open() method inside a click handler or any function which will be triggered by a user.

The browser will block all other invocation of the window.open() methods that are not triggered by the user.

This feature is implemented to reduce the abuse of opening tabs automatically when a user visits a website for showing ads and spam etc.

For example, Consider a button where if we click on it will open a new tab with https://google.com url. Let's give the button an id of googleBtn liek this,

<!-- Button which open google.com -->
<button id="googleBtn">Open Google<button /></button>
Enter fullscreen mode Exit fullscreen mode

First let's get the reference to the button,

// get refernce to the button
const googleBtn = document.getElementById("googleBtn");
Enter fullscreen mode Exit fullscreen mode

Now let's add a click event handler to the button so that when the user clicks it will invoke the window.open() method with URL https://google.com.

NOTE: If the window.open() method is not inside a function that is not triggered by a user, the browser will block it saying it is a popup.

// get refernce to the button
const googleBtn = document.getElementById("googleBtn");

// add click event handler to button
googleBtn.addEventListener("click", () => {
  window.open("https://google.com");
});
Enter fullscreen mode Exit fullscreen mode

Now if you click on the button, the browser will open a new tab with the URL without blocking it.

See this example live in JSBin.

Feel free to share if you found this useful 😃.


Top comments (0)