Monday, May 20, 2024
30
rated 0 times [  35] [ 5]  / answers: 1 / hits: 131162  / 12 Years ago, wed, may 30, 2012, 12:00:00

Using javascript, I want to open a new page in a different tab, but remain focused on the current tab. I know I can do it like this:



open('http://example.com/');
focus();


However, when I do this in chrome, it flashes the new tab for a moment before switching back to the current tab. I want to avoid this.



The application is a personal bookmarklet, so it only has to work in the latest Chrome.


More From » google-chrome

 Answers
12

UPDATE: By version 41 of Google Chrome, initMouseEvent seemed to have a changed behavior, and so this answer no longer works. Thanks to @Daniel Andersson for his comment.


this can be done by simulating ctrl + click (or any other key/event combinations that open a background tab) on a dynamically generated a element with its href attribute set to the desired url


In action: fiddle


function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = "http://www.google.com/";
var 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);
a.dispatchEvent(evt);
}

tested only on chrome


[#85272] Monday, May 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
asalewisc

Total Points: 742
Total Questions: 98
Total Answers: 112

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
;