24

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.
Gabe
  • 5,997
  • 5
  • 46
  • 92
  • Why do you need to do that? I ask this because maybe what you're trying to do (maybe some background processing?) could be achieved executing javascript code with Node.js. Usually browsers do not allow to open tabs in that way for a security/spam reason. – fsinisi90 Aug 14 '18 at 18:22
  • @fsinisi90 yes, I know. Using node would solve the issue but I would have to re-write the system from scratch. It's on my todo list but only when and if the current solution breaks. Regarding the security reason yes I'm aware of that but the plugin after all does it anyway. Only it leaves focus on another tab (the last used one actually, not the one that launched the new tab). Thanks anyway – Gabe Aug 14 '18 at 19:53
  • What does opening the new tab achieve for you? For example, might you open an iframe in the current tab instead? What you're looking for might not be possible via Javascript alone, but it might be doable with something that does OS scripting like AutoHotKey. – CertainPerformance Aug 18 '18 at 22:46
  • If you want background processing use webworkers. Opening sneaky tabs in the background is what malicious apps always try. I hate that when that happens and close those ASAP as soon as I saw the flicker of a tab opening. – Tschallacka Aug 21 '18 at 11:20
  • @CertainPerformance no, I thought about the iframe solution but it would not work for me. Thanks for that, I'll take at AutoHotKey. – Gabe Aug 21 '18 at 17:57
  • @Tschallacka yes that would be the right solution if the script didn't have to interact with the UI.. – Gabe Aug 21 '18 at 17:57
  • Thats why you would write logic that would request data and then put data back for what should be happening visually. – Tschallacka Aug 21 '18 at 18:02
  • @Tschallacka the issue is that both the tab that execute the script and the tab opened programmatically need to interact with the UI. Wouldn't work in my case. Thanks anyway! :) – Gabe Aug 22 '18 at 04:59

4 Answers4

14

As you want this for personal usage, and you do not mind using an extension, then you can write your own one.

Writing a chrome extension to achieve your required behavior is actually super easy, All you need to know is how to open/close tabs from the extension. The following page describes the whole API

Here is an example :

1 - Create a manifest.json file, and ask for the tabs permission

{
  "name": "blabla",
  "version": "0.1",
  "permissions": ["tabs"],
  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_title": "Open a background tab every x time"
  },
  "manifest_version": 2
}

2 - Create background.js script in the same folder

const INTERVAL = 5000;
setTimeout(function(){
    chrome.tabs.create({url: "https://www.stackoverflow.com", active: false }, tab =>{
        setTimeout(function(){
            chrome.tabs.remove(tab.id);
        },INTERVAL);
    }); 
},INTERVAL);

You can download it from here too

Note: Please note the active parameter here , it defines whether the tab should become the active tab in the window. Does not affect whether the window is focused

3 - Use the extension in chrome

  1. If you are using the download link, then unpack the archive
  2. Navigate from chrome menu to extensions
  3. Enable the developer mode in the top right corner
  4. Click on Load Unpacked button to select the extension folder
  5. The extension will run automatically
Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
5

In the old days, you could do this using stuff like :

if(window.focus == false)
{
    this.focus();
}


Now you have to use extra plugins, due to abusers.
The Solution: Window Rollover:
The solution is to create another page. When you click the link, the window closes, it switches to a page that opens the window that just closed, and changes it's location to the new page.
Page 1 code:

document.getElementById("myId").onclick = function(){window.open("page2.html");window.close()}

Page 2 code:

window.open("previouspage.html");
window.location = "newpage.html";
//close the page
window.close();

I call this strategy "Window Rollover."

bluninja1234
  • 73
  • 10
  • 3
    Nice, but this is more like "Eye Roll-over" with all these redirections and loads. – BaSsGaz Apr 21 '19 at 12:41
  • @Anthony I've seen some websites use this kind of method. I wrote this a long time ago, so I'm not too sure if it works now. I think I tested it before, however. – bluninja1234 Jul 11 '20 at 05:35
4

I PARTIALLY resolved using a Chrome plugin: Force Background Tab

https://chrome.google.com/webstore/detail/force-background-tab/gidlfommnbibbmegmgajdbikelkdcmcl/related?hl=en

Using that add-on the tab is opened in background without focus. The only issue is that the last used tab of the window (can be different from the tab that launches the new tab) still pops up in front of any other application in use.

Gabe
  • 5,997
  • 5
  • 46
  • 92
  • 1
    Using extension isn't recommended as it's not client friendly, you cannot tell every client to download the extension. – Barr J Aug 14 '18 at 17:39
  • 1
    @BarrJ I don't mind, I'm the only user. It's for personal use. – Gabe Aug 14 '18 at 20:26
2

You can try a kind of pop under, where you open the same url in a new tab, then change the location.href of current tab to the desired new url.

window.open(window.location.href);
window.location.href = 'http://www.google.com';
Adriaan
  • 17,741
  • 7
  • 42
  • 75