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

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

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

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


当前回答

window.open(url)将在一个新的浏览器选项卡中打开url。下面是替代它的JavaScript:

let a = document.createElement('a');
a.target = '_blank';
a.href = 'https://support.wwf.org.uk/';
a.click(); // We don't need to remove 'a' from the DOM, because we did not add it

这里是一个工作示例(StackOverflow片段不允许打开新选项卡)。

其他回答

只要省略strWindowFeatures参数,就会打开一个新选项卡,除非浏览器设置覆盖它(浏览器设置胜过JavaScript)。

新建窗口

var myWin = window.open(strUrl, strWindowName, [strWindowFeatures]);

新建选项卡

var myWin = window.open(strUrl, strWindowName);

--或--

var myWin = window.open(strUrl);

要打开新选项卡并保持在同一位置,可以在新选项卡中打开当前页面,然后将旧选项卡重定向到新URL。

let newUrl = 'http://example.com';
let currentUrl = window.location.href;
window.open(currentUrl , '_blank'); // Open window with the URL of the current page
location.href = newUrl; // Redirect the previous window to the new URL

浏览器将自动将您移动到新打开的选项卡。看起来您的页面已重新加载,您将停留在同一页面上,但在新窗口上:

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

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

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

如果链接位于同一域(同一网站),浏览器将始终在新选项卡中打开该链接。如果链接在其他域上,它将在新的选项卡/窗口中打开,具体取决于浏览器设置。

因此,根据这一点,我们可以使用:

<a class="my-link" href="http://www.mywebsite.com" rel="http://www.otherwebsite.com">new tab</a>

并添加一些jQuery代码:

jQuery(document).ready(function () {
    jQuery(".my-link").on("click",function(){
        var w = window.open('http://www.mywebsite.com','_blank');
        w.focus();
        w.location.href = jQuery(this).attr('rel');
        return false;
    });
});

所以,首先用_blank target在同一个网站上打开新窗口(它将在新选项卡中打开),然后在新窗口中打开您想要的网站。

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

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

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

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