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

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

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

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


当前回答

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

其他回答

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

你可以在形式上使用技巧:

$(function () {
    $('#btn').click(function () {
        openNewTab("http://stackoverflow.com")
        return false;
    });
});

function openNewTab(link) {
    var frm = $('<form   method="get" action="' + link + '" target="_blank"></form>')
    $("body").append(frm);
    frm.submit().remove();
}

jsFiddle演示

不要使用target=“_blank”

始终为该窗口使用一个特定的名称,在我的情况下是指fulName。在这种情况下,可以节省处理器资源:

button.addEventListener('click', () => {
    window.open('https://google.com', 'meaningfulName')
})

这样,例如,当你在一个按钮上单击10次时,浏览器将始终在一个新选项卡中重新阅读它,而不是在10个不同的选项卡中打开它,这将消耗更多的资源。

您可以在MDN上阅读有关此的更多信息。

如果您只想打开外部链接(指向其他站点的链接),那么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');
        }
    });
});

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

更新

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

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