在后台打开一个新标签?

st-*_*ost 71 javascript google-chrome

使用javascript,我想在不同的选项卡中打开一个新页面,但仍然专注于当前选项卡.我知道我可以这样做:

open('http://example.com/');
focus();
Run Code Online (Sandbox Code Playgroud)

但是,当我在chrome中执行此操作时,它会在切换回当前选项卡之前将新选项卡闪烁一会儿.我想避免这种情况.

该应用程序是一个个人书签,因此它只需要在最新的Chrome中工作.

Amr*_*mro 99

更新:在谷歌浏览器版本41中, initMouseEvent 似乎有一个改变的行为.

这可以通过在动态生成的元素上模拟ctrl+ click(或打开背景选项卡的任何其他键/事件组合)a并将其href属性设置为所需的值来完成url

在行动: 小提琴

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);
}
Run Code Online (Sandbox Code Playgroud)

仅在铬上测试过

  • 这似乎已停止使用2014年11月20日发布的谷歌Chrome开发版41.0.2224.0(在Linux上测试).这并不奇怪,因为我认为它首先是"非预期的功能",但令人讨厌,因为我在本地应用程序中很好地使用它.Chrome的稳定和测试版渠道应该不会受到影响,但可能会很快合并这些更改. (22认同)
  • 真棒,我想我们得到了它.但重要的是:在OSX上,metaKey值必须为true. (8认同)
  • 从今天开始还没有工作。 (6认同)
  • 另一个注意事项:这不适用于具有锚文本的URL,除非你设置`a.target ='_ blank';`. (4认同)
  • @ maggot092使用`MouseEvent('click',{view:window,ctrlKey:true,metaKey:true});`,新打开的标签仍然窃取焦点.我错过了什么吗? (4认同)
  • 不适用于Chrome版本55 (2认同)

use*_*849 8

THX这个问题!在所有流行的浏览器上对我有用:

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 从MDN“已弃用此功能已从Web标准中删除。尽管某些浏览器可能仍支持此功能,但该功能正在被删除。请勿在新旧项目中使用它。使用它的页面或Web应用程序可能会在任何时间。” (2认同)