Sometimes, we want to open a new tab in the background with JavaScript.
In this article, we’ll look at how to open a new tab in the background with JavaScript.
How to open a new tab in the background with JavaScript?
To open a new tab in the background with JavaScript, we can simulate pressing ctrl-click on a link programmatically.
For instance, we write
const a = document.createElement("a");
a.href = "http://www.example.com/";
const evt = document.createEvent("MouseEvents");
evt.initMouseEvent(
"click",
true,
true,
window,
0,
0,
0,
0,
0,
true,
false,
false,
false,
0,
null
);
a.dispatchEvent(evt);
to call createElement to create a link.
We set its href property to the URL we want to go to.
Then we call createEvent to create a mouse event.
And we call initMouseEvent to create a mouse event with the 10th argument set to true to enable pressing ctrl.
Next, we call dispatchEvent with evt to dispatch the mouse event to open the link in the background.
Conclusion
To open a new tab in the background with JavaScript, we can simulate pressing ctrl-click on a link programmatically.