How to execute in JavaScript a CTRL + click on a link that works in the latest version of Chrome (v68)?
Context - I'm running a JavaScript script that opens a certain tab at certain hours of the day (and closes it after a few minutes). I'm trying to get it to open the tab in background leaving the focus on the current tab that I'm using.
The tab opened programmatically leads Chrome to pop up even when minimized, quite disrupting.
These old solutions that I found here on Stack Overflow don't work with the latest version of Chrome.
Manually CTRL + clicking a link achieves the effect that I want (tab is opened in background). Can this be achieved programmatically on the latest version of Chrome?
The following code does not work anymore with the latest version of Chrome..
const openNewBackgroundTab = (url) => {
const anchor = document.createElement("a");
anchor.href = url;
document.body.appendChild(anchor);
const evt = document.createEvent("MouseEvents");
// the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent(
"click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null
);
anchor.dispatchEvent(evt);
}
openNewBackgroundTab('https://stackoverflow.com');
.. the new tab still gets the focus.
STEPS to reproduce:
- Open window 1 and in console execute:
let winStacko;
setTimeout(() => { winStacko = open('https://www.stackoverflow.com'); }, 30 * 1000);
setTimeout(() => winStacko.close(), 2 * 60 * 1000);
- Open window 2 within 30 seconds after executing the script
DESIRED behavior:
- Window 2 has the focus for the whole time while the background tab is opened and then closed.