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

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

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

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


当前回答

这将创建一个虚拟的a元素,并为其提供target=“_blank”,因此它将在一个新选项卡中打开,为其提供适当的URL href,然后单击它。

function openInNewTab(href) {
  Object.assign(document.createElement('a'), {
    target: '_blank',
    rel: 'noopener noreferrer',
    href: href,
  }).click();
}

然后你可以像这样使用它:

openInNewTab("https://google.com");

重要说明:

这必须在所谓的“可信事件”回调过程中调用,例如,在单击事件期间(在回调函数中不需要直接调用,但在单击操作期间)。否则,浏览器将阻止打开新页面。

如果您在某个随机时刻手动调用它(例如,在一段时间内或在服务器响应之后),它可能会被浏览器阻止(这很有道理,因为这会带来安全风险,并可能导致用户体验不佳)。

其他回答

如果您只想打开外部链接(指向其他站点的链接),那么JavaScript/jQuery的这一功能很好:

$(function(){
    var hostname = window.location.hostname.replace('www.', '');
    $('a').each(function(){
        var link_host = $(this).attr('hostname').replace('www.', '');
        if (link_host !== hostname) {
            $(this).attr('target', '_blank');
        }
    });
});

如果您使用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;
};

如何创建一个<a>,其中_blank作为目标属性值,url作为href,样式显示:隐藏在a子元素中?然后添加到DOM,然后在子元素上触发单击事件。

更新

这行不通。浏览器会阻止默认行为。它可以通过编程方式触发,但不遵循默认行为。

自己检查一下:http://jsfiddle.net/4S4ET/

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

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

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

我将在一定程度上同意下面的人的观点(此处转述):“对于现有网页中的链接,如果新网页与现有网页是同一网站的一部分,浏览器将始终在新选项卡中打开链接。”至少对我来说,这条“通用规则”适用于Chrome、Firefox、Opera、Internet Explorer、Safari、SeaMonkey和Konqueror。

不管怎样,有一种不那么复杂的方法可以利用对方所呈现的内容。假设我们讨论的是您自己的网站(下面的“thisite.com”),您希望在其中控制浏览器的功能,那么,下面,您希望“specialpage.htm”为空,其中完全没有HTML(这样可以节省从服务器发送数据的时间!)。

 var wnd, URL; // Global variables

 // Specifying "_blank" in window.open() is SUPPOSED to keep the new page from replacing the existing page
 wnd = window.open("http://www.thissite.com/specialpage.htm", "_blank"); // Get reference to just-opened page
 // If the "general rule" above is true, a new tab should have been opened.
 URL = "http://www.someothersite.com/desiredpage.htm";  // Ultimate destination
 setTimeout(gotoURL(), 200);  // Wait 1/5 of a second; give browser time to create tab/window for empty page


 function gotoURL()
 { 
   wnd.open(URL, "_self");  // Replace the blank page, in the tab, with the desired page
   wnd.focus();             // When browser not set to automatically show newly-opened page, this MAY work
 }