使用 javascript,我想在不同的选项卡中打开一个新页面,但仍专注于当前选项卡。我知道我可以这样做:
open('http://example.com/');
focus();
但是,当我在 chrome 中执行此操作时,它会在切换回当前选项卡之前闪烁一下新选项卡。我想避免这种情况。
该应用程序是一个个人书签,因此它只需要在最新的 Chrome 中运行。
使用 javascript,我想在不同的选项卡中打开一个新页面,但仍专注于当前选项卡。我知道我可以这样做:
open('http://example.com/');
focus();
但是,当我在 chrome 中执行此操作时,它会在切换回当前选项卡之前闪烁一下新选项卡。我想避免这种情况。
该应用程序是一个个人书签,因此它只需要在最新的 Chrome 中运行。
更新: 由于@Daniel Andersson ,Google 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);
}
仅在 chrome 上测试
谢谢这个问题!在所有流行的浏览器上对我都有好处:
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 首选项中:
注意最后一个选项。
我以一种非常简单的方式做了你正在寻找的东西。它在 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 行)
您可能唯一不喜欢的是新选项卡在主页之前打开。
这是在具有焦点的新选项卡上导航有效 URL 的完整示例。
HTML:
<div class="panel">
<p>
Enter Url:
<input type="text" id="txturl" name="txturl" size="30" class="weburl" />
<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;
}
Java脚本:
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