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

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

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

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


当前回答

这是一个技巧,

function openInNewTab(url) {
  window.open(url, '_blank').focus();
}

// Or just
window.open(url, '_blank').focus();

在大多数情况下,这应该直接发生在链接的onclick处理程序中,以防止弹出窗口阻止程序和默认的“新窗口”行为。您可以这样做,或者向DOM对象添加事件侦听器。

<div onclick="openInNewTab('www.test.com');">Something To Click On</div>

参考:使用JavaScript在新选项卡中打开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片段不允许打开新选项卡)。

下面是一个如何将其放入HTML标记的示例

<button onClick="window.open('https://stackoverflow.com/','_blank')">Stackoverflow</button>

我将在一定程度上同意下面的人的观点(此处转述):“对于现有网页中的链接,如果新网页与现有网页是同一网站的一部分,浏览器将始终在新选项卡中打开链接。”至少对我来说,这条“通用规则”适用于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
 }

我使用了以下方法,效果很好!

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

这种方式与以前的解决方案类似,但实施方式不同:

.social_icon->CSS类

 <div class="social_icon" id="SOME_ID" data-url="SOME_URL"></div>

 $('.social_icon').click(function(){

        var url = $(this).attr('data-url');
        var win = window.open(url, '_blank');  ///similar to above solution
        win.focus();
   });