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
like this,
<!-- Button which open google.com -->
<button id="googleBtn">Open Google<button /></button>
First let's get the reference to the button,
// get refernce to the button
const googleBtn = document.getElementById("googleBtn");
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");
});
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.