我试图在一个新的选项卡中打开一个URL,而不是弹出窗口。

我见过一些相关的问题,其中的回答大致如下:

window.open(url,'_blank');
window.open(url);

但没有一个对我有效,浏览器仍然试图打开一个弹出窗口。


当前回答

在Firefox(Mozilla)扩展中打开一个新的选项卡如下:

gBrowser.selectedTab = gBrowser.addTab("http://example.com");

其他回答

这个问题有答案,但不是否定的。

我找到了一个简单的解决方法:

步骤1:创建不可见链接:

<a id=“yourId”href=“yourlink.html”target=“_blank”style=“display:none;”></a>

步骤2:以编程方式单击该链接:

document.getElementById(“yourId”).click();

干得好!这对我很有吸引力。

有很多答案副本建议使用“_blank”作为目标,但我发现这并不奏效。正如Prakash指出的,这取决于浏览器。但是,您可以向浏览器提出某些建议,例如窗口是否应具有位置栏。

如果你提出了足够多的“类似标签的东西”,你可能会得到一个标签,正如Nico对铬的这个更具体问题的回答:

window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');

免责声明:这不是万能药。这仍然取决于用户和浏览器。现在,至少您为希望窗口的外观指定了一个首选项。

作者无法选择在新选项卡而不是新窗口中打开;这是用户偏好。(请注意,大多数浏览器中的默认用户首选项是针对新选项卡的,因此在未更改该首选项的浏览器上进行的简单测试不会证明这一点。)

CSS3提出了新的目标,但该规范被放弃。

反之则不然;通过在window.open()的第三个参数中为窗口指定某些窗口特性,当首选项是选项卡时,可以触发一个新窗口。

function openTab(url) {
  const link = document.createElement('a');
  link.href = url;
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();
  link.remove();
}

如果您使用window.open(url,'_blank'),它将在Chrome上被阻止(弹出窗口阻止程序)。

试试看:

//With JQuery

$('#myButton').click(function () {
    var redirectWindow = window.open('http://google.com', '_blank');
    redirectWindow.location;
});

使用纯JavaScript,

document.querySelector('#myButton').onclick = function() {
    var redirectWindow = window.open('http://google.com', '_blank');
    redirectWindow.location;
};