在后台打开一个新标签?

使用JavaScript,我想打开一个新的页面在不同的标签,但仍然关注当前标签。 我知道我可以这样做:

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

但是,当我使用chrome进行这个操作时,在切换回当前选项卡之前,会闪烁新的选项卡片刻。 我想避免这一点。

该应用程序是一个个人书签,所以它只能在最新的Chrome中工作。

更新:在谷歌浏览器版本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); } 

仅在铬上进行测试

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(); } 

据我所知,这是由浏览器设置控制。 换句话说:用户可以选择是否要在后台或前台打开新选项卡。 他们也可以选择是否在新标签中打开新的弹出窗口或弹出窗口。

例如在Firefox的首选项:

Firefox设置示例

注意最后一个选项。

尝试这个。 它适用于Chrome,它也从铬扩展工作。 以上所有都不适合我。

 chrome.tabs.create({"url": "http://www.google.com/", "selected": false}); 

这里是一个完整的示例,用于在新的选项卡上导航有效的URL。

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; } } 

我也用http://codebins.com/codes/home/4ldqpbw上的解决方案创建了一个bin

我以一种非常简单的方式做了你正在寻找的东西。 在Google Chrome和Opera中非常流畅,在Firefox和Safari中几乎完美。 没有在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; } 

小提琴: http : //jsfiddle.net/tFCnA/show/

说明:
假设有窗口A1和B1以及网站A2和B2。
不是在B1中打开B2然后返回A1,而是在A1中打开B2并在B1中重新打开A2。
(使它工作的另一件事是,我不让用户重新下载A2,见第4行)


可能不喜欢的唯一的事情就是新标签在主页面之前打开。