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

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

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

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


当前回答

jQuery

$('<a />',{'href': url, 'target': '_blank'}).get(0).click();

JavaScript

Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();

其他回答

不要使用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');
        }
    });
});

我认为你无法控制这一切。如果用户已将浏览器设置为在新窗口中打开链接,则不能强制其在新选项卡中打开链接。

JavaScript在新窗口中打开,而不是选项卡

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

一个有趣的事实是,如果用户未调用该操作(单击按钮或其他东西),或者该操作是异步的,则无法打开新选项卡,例如,这将不会在新选项卡中打开:

$.ajax({
    url: "url",
    type: "POST",
    success: function() {
        window.open('url', '_blank');              
    }
});

但这可能会在新选项卡中打开,具体取决于浏览器设置:

$.ajax({
    url: "url",
    type: "POST",
    async: false,
    success: function() {
        window.open('url', '_blank');              
    }
});