JavaScript中window.location在新标签页打开

211

我通过window.location将用户重定向到某个url,但是该url在浏览器的同一标签页中打开。我想让它在新标签页中打开。我能否使用window.location实现这一点?还有其他方法可以完成此操作吗?


3
请问您需要将以下内容翻译成中文吗?Duplicate: https://dev59.com/lXRC5IYBdhLWcg3wCMrX - Samich
1
window.location 是必须的吗?或者其他 JS 解决方案可行吗? - Khez
@Khez:其他的JS可以提供。 - Muhammad Imran Tariq
你可以使用window.open()。 - Junaid khan
8个回答

584
window.open('https://support.wwf.org.uk', '_blank');

第二个参数是使其在新窗口中打开的原因。别忘了阅读Jakob Nielsen的信息文章 :)


11
如果您的浏览器已经阻止了弹出框设置,那该怎么办?这将不起作用。 - pregmatch
@Alex 嗯...不是很“正确”的答案。在Firefox中尝试,因为我阻止弹出窗口,所以这段代码失败了。 - TARKUS

60
你甚至可以使用

window.open('https://support.wwf.org.uk', "_blank") || window.location.replace('https://support.wwf.org.uk');

如果弹窗被阻止,这将在同一标签页打开它。


我会避免使用这种解决方案,因为在某些情况下,window.open可能会返回null(但仍然按预期打开新窗口),同时还会触发当前标签页上的location.replace,导致两个带有新URL的打开标签页。使用此答案中描述的try/catch可能是更好的解决方案https://dev59.com/0XVD5IYBdhLWcg3wXaYd#27725432。 - Troy Watt

52

我认为除非你编写浏览器扩展程序,否则没有办法做到这一点。你可以尝试使用 window.open 方法,并希望用户的浏览器设置为在新标签页中打开新窗口。


不需要抱有希望,只需将**_blank**作为第二个参数传递即可 :) window.open(url, '_blank'); - undefined

22

这对我在 Chrome 53 上有效。在其他地方没有测试过:

function navigate(href, newTab) {
   var a = document.createElement('a');
   a.href = href;
   if (newTab) {
      a.setAttribute('target', '_blank');
   }
   a.click();
}

12

使用jQuery会更加容易,并且在Chrome上也可以工作

$('#your-button').on('click', function(){
       $('<a href="https://www.some-page.com" target="blank"></a>')[0].click();    
})

8

相比于使用弹出窗口,我个人更喜欢这种解决方案,它在这个问题的讨论串中被提到: JavaScript:location.href打开新的窗口/选项卡?

$(document).on('click','span.external-link',function(){
        var t               = $(this), 
            URL             = t.attr('data-href');        
        $('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();

    });

这是一个关于it技术的 示例


1
let url = 'yourUrl?Param=' + Param;
window.open(url, '_blank');

0

我们需要动态设置属性target="_blank",这样它就会在新标签页中打开。 document.getElementsByTagName("a")[0].setAttribute('target', '_blank')

document.getElementsByTagName("a")[0].click()

如果想在新窗口打开,获取 href 链接并使用 window.open

var link = document.getElementsByTagName("a")[0].getAttribute("href");

window.open(url, "","height=500,width=500");

请勿在上述代码中提供第二个参数作为 _blank。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接