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

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

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

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


当前回答

这对我有效。只需阻止事件,将URL添加到<a>标记,然后在该标记上触发单击事件。

JavaScript

$('.myBtn').on('click', function(event) {
        event.preventDefault();
        $(this).attr('href', "http://someurl.com");
        $(this).trigger('click');
});

HTML

<a href="#" class="myBtn" target="_blank">Go</a>

其他回答

如果您只想打开外部链接(指向其他站点的链接),那么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');
        }
    });
});
function openTab(url) {
  const link = document.createElement('a');
  link.href = url;
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();
  link.remove();
}

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

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

<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在同一个网站上打开新窗口(它将在新选项卡中打开),然后在新窗口中打开您想要的网站。

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

.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();
   });

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

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