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

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

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

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


当前回答

是否在新选项卡或新窗口中打开URL,实际上由用户的浏览器首选项控制。无法在JavaScript中覆盖它。

window.open()的行为取决于它的使用方式。如果它是作为用户操作的直接结果调用的,让我们假设单击一个按钮,它应该可以正常工作并打开一个新的选项卡(或窗口):

const button = document.querySelector('#openTab');

// add click event listener
button.addEventListener('click', () => {
    // open a new tab
    const tab = window.open('https://attacomsian.com', '_blank');
});

但是,如果您尝试从AJAX请求回调打开新选项卡,浏览器将阻止它,因为它不是直接的用户操作。

要绕过弹出窗口阻止程序并从回调中打开新选项卡,这里有一个小技巧:

const button = document.querySelector('#openTab');

// add click event listener
button.addEventListener('click', () => {

    // open an empty window
    const tab = window.open('about:blank');

    // make an API call
    fetch('/api/validate')
        .then(res => res.json())
        .then(json => {

            // TODO: do something with JSON response

            // update the actual URL
            tab.location = 'https://attacomsian.com';
            tab.focus();
        })
        .catch(err => {
            // close the empty window
            tab.close();
        });
});

其他回答

为了阐述史蒂文·斯皮尔伯格的答案,我在这样一个案例中这样做了:

$('a').click(function() {
  $(this).attr('target', '_blank');
});

这样,就在浏览器跟随链接之前,我正在设置目标属性,因此它将在新的选项卡或窗口中打开链接(取决于用户的设置)。

jQuery中的一行示例:

$('a').attr('target', '_blank').get(0).click();
// The `.get(0)` must be there to return the actual DOM element.
// Doing `.click()` on the jQuery object for it did not work.

这也可以通过使用本机浏览器DOM API来实现:

document.querySelector('a').setAttribute('target', '_blank');
document.querySelector('a').click();

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

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

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

如果您试图从自定义功能打开新选项卡,则这与浏览器设置无关。

在此页面中,打开JavaScript控制台并键入:

document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").click();

它会尝试打开一个弹出窗口,而不管您的设置如何,因为“点击”来自自定义操作。

为了表现得像一个链接上的实际“鼠标点击”,您需要遵循spirinvradimir的建议并真正创建它:

document.getElementById("nav-questions").setAttribute("target", "_blank");
document.getElementById("nav-questions").dispatchEvent((function(e){
  e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                    false, false, false, false, 0, null);
  return e
}(document.createEvent('MouseEvents'))));

这里有一个完整的示例(不要在jsFiddle或类似的在线编辑器上尝试,因为它不会让您从那里重定向到外部页面):

<!DOCTYPE html>
<html>
<head>
  <style>
    #firing_div {
      margin-top: 15px;
      width: 250px;
      border: 1px solid blue;
      text-align: center;
    }
  </style>
</head>

<body>
  <a id="my_link" href="http://www.google.com"> Go to Google </a>
  <div id="firing_div"> Click me to trigger custom click </div>
</body>

<script>
  function fire_custom_click() {
    alert("firing click!");
    document.getElementById("my_link").dispatchEvent((function(e){
      e.initMouseEvent("click", true, true, window, /* type, canBubble, cancelable, view */
            0, 0, 0, 0, 0,              /* detail, screenX, screenY, clientX, clientY */
            false, false, false, false, /* ctrlKey, altKey, shiftKey, metaKey */
            0, null);                   /* button, relatedTarget */
      return e
    }(document.createEvent('MouseEvents'))));
  }
  document.getElementById("firing_div").onclick = fire_custom_click;
</script>
</html>

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

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