89

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.

st-boost
  • 1,877
  • 1
  • 14
  • 17
  • http://www.w3schools.com/js/js_ex_browser.asp try any of these – Code Spy May 30 '12 at 08:56
  • 1
    @jolly.exe Thanks, but none of those avoid momentarily showing the new page in chrome. – st-boost May 30 '12 at 09:48
  • 3
    Seems a duplicate of this question http://stackoverflow.com/questions/6897430/prevent-window-open-from-focusing Solution is to use the Chrome extension api. – Willem Joosten Jul 04 '12 at 07:43
  • @WillemJoosten thanks for the first answer that has actually accomplished the goal. But is there some way to do this outside of an extension? The benefit is so small that it would be outweighed by the time it takes to install the extension. – st-boost Jul 04 '12 at 11:51
  • Possible duplicate of [Prevent window.open from focusing](https://stackoverflow.com/questions/6897430/prevent-window-open-from-focusing) – mariotomo Jul 06 '19 at 20:03

6 Answers6

113

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

Flimm
  • 136,138
  • 45
  • 251
  • 267
Amro
  • 1,644
  • 1
  • 11
  • 13
  • 9
    Awesome, I think we got it. An important note though: on OSX it's the metaKey value that needs to be true. – st-boost Jul 09 '12 at 10:01
  • 4
    Another note: this will not work with URLs that have anchor text unless you set `a.target='_blank';`. – st-boost Jul 09 '12 at 10:04
  • 1
    This is of great help. You're awesome :D – iAnuj Aug 16 '12 at 03:42
  • This will be blocked by the popup blocker in Chrome, sadly. – Skynet Sep 09 '13 at 19:43
  • Doesn't work and doesn't even activate popup-blocker in Chrome 33. – JohnK Mar 17 '14 at 21:46
  • Works fine for me, chrome 33.0.1750.154, windows 7 – Amro Mar 21 '14 at 22:33
  • Working in Chrome 34. Not blocked by the popup blocker. – Magne Apr 23 '14 at 07:24
  • 1
    With the metaKey value set (13th parameter), as suggested: `evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, true, 0, null);` – Magne Apr 23 '14 at 07:26
  • Not working in FF 28 here either. `Error: Permission denied to access property 'document'` – Magne Apr 23 '14 at 07:43
  • MASTER MIND ... Unbelievable.... Working very fine for chrome.. we can use it by detect browser. – Amrish Prajapati Jul 30 '14 at 19:18
  • 28
    This seems to have stopped working with Google Chrome dev release 41.0.2224.0, released 2014-11-20 (tested on Linux). Not surprising since I guess it was "unintended functionality" to begin with, but annoying since I had great use of it in local applications. The stable and beta channels of Chrome should be unaffected as of yet, but will probably merge the changes soon. – Daniel Andersson Dec 01 '14 at 12:02
  • Due to [MDN](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent) initMouseEvent is deprecated. Use `new MouseEvent("click", {clientX: x, clientY: y, ctrlKey: true})` instead. – sbeliakov Jun 18 '15 at 18:21
  • 7
    @maggot092 using `MouseEvent('click', {view: window, ctrlKey: true, metaKey: true});`, the newly opened tab still steals the focus. Am I missing something? – Stepan Parunashvili Jul 16 '15 at 00:31
  • 5
    Not working as of today. – Mark Jan 27 '22 at 21:07
  • 1
    I got it working by adding the A element to the current document, dispatching the event and then removing the element again. At least that made it work in Firefox, but I'm running an older 91~something version, so maybe that won't even work anymore in the newer ones. Gotta love web design. – BloodyRain2k Dec 10 '22 at 19:44
8

This works well for me on all popular browsers:

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = window.location.pathname;
    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);
}

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
    var url = window.location.pathname;
    var win = window.open(url, '_blank');
} else {
    openNewBackgroundTab();
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
user2837849
  • 319
  • 1
  • 3
  • 8
  • 4
    From MDN "Deprecated This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time." – BaSsGaz Mar 22 '15 at 11:15
1

Here is an example in MountEvent

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example</title>
</head>
<script>
  function newTab() {
    const a = document.createElement('a');
    a.href = 'https://example.com/';
    a.target = '_blank';
    const e = new MouseEvent('click', {
      ctrlKey: true, // for Windows or Linux
      metaKey: true, // for MacOS
    });
    a.dispatchEvent(e);
  }
</script>

<body>

  <button onclick="newTab()">new tab</button>
</body>

</html>
DCjanus
  • 394
  • 5
  • 9
0

As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.

For example in firefox preferences:

Firefox setup example

Notice the last option.

demee
  • 582
  • 5
  • 18
  • 3
    Thanks, but I'm hoping for something I can control from within a website, as I don't want this to affect other websites. (also, ctrl/cmd + click does the same thing - I use it all the time) – st-boost Jul 03 '12 at 19:59
  • 1
    this is not for javascript, just only for browser setting. – Lin Feb 20 '18 at 01:56
0

I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.


function newTab(url)
{
    var tab=window.open("");
    tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
    tab.document.close();
    window.location.href=url;
}

Fiddle : http://jsfiddle.net/tFCnA/show/

Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)


The only thing you may doesn't like is that the new tab opens before the main page.

Alexandre Khoury
  • 3,896
  • 5
  • 37
  • 58
  • 1
    Thank you, that's a clever approach. However, it has a number of problems, including clobbering event listeners, misaligning browser history, potentially changing the doctype, and discarding attributes on the html element, not to mention the fact that it doesn't actually "open a new page in a different tab". – st-boost Jul 05 '12 at 05:58
  • Why doesn't it open a new page in a different tab? – Alexandre Khoury Jul 05 '12 at 08:09
  • 4
    Well technically it opens the new page in the same tab, and the same page in a new tab. I know that's just grammar that doesn't matter - what does matter is that this disassociates the page from its history (breaks the back button) and makes it a lot harder for chrome etc to keep track of tab hierarchy. – st-boost Jul 05 '12 at 10:06
-3

Here is a complete example for navigating valid URL on a new tab with focused.

HTML:

<div class="panel">
  <p>
    Enter Url: 
    <input type="text" id="txturl" name="txturl" size="30" class="weburl" />
    &nbsp;&nbsp;    
    <input type="button" id="btnopen"  value="Open Url in New Tab" onclick="openURL();"/>
  </p>
</div>

CSS:

.panel{
  font-size:14px;
}
.panel input{
  border:1px solid #333;
}

JAVASCRIPT:

function isValidURL(url) {
    var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

    if (RegExp.test(url)) {
        return true;
    } else {
        return false;
    }
}

function openURL() {
    var url = document.getElementById("txturl").value.trim();
    if (isValidURL(url)) {
        var myWindow = window.open(url, '_blank');
        myWindow.focus();
        document.getElementById("txturl").value = '';
    } else {
        alert("Please enter valid URL..!");
        return false;
    }
}

I have also created a bin with the solution on http://codebins.com/codes/home/4ldqpbw

gaurang171
  • 9,032
  • 4
  • 28
  • 30
  • 2
    Thank you, but I think you misunderstand my question. I want the opener page to be the one focused in the end, not the new tab - and the question is how I can avoid displaying the new tab for even a moment. – st-boost Jul 03 '12 at 19:54
  • As of today and the latest Chrome, this doesn't seem to do anything at all. – Mr Printer May 10 '19 at 19:11