javascript窗口。新标签中的位置

我正在通过window.location转移用户到一些url,但这个url在浏览器的同一选项卡中打开。我希望它在新标签打开。我可以用window。location这样做吗?还有其他方法来做这个动作吗?

321153 次浏览

我认为没有办法做到这一点,除非您正在编写浏览器扩展。你可以尝试使用window.open,并希望用户的浏览器设置为在新选项卡中打开新窗口。

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

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

这适用于我的Chrome 53。还没有在其他地方测试过:

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

使用jQuery,它甚至更容易,并在Chrome上工作

$('#your-button').on('click', function(){
$('<a href="https://www.some-page.com" target="blank"></a>')[0].click();
})
比起弹出窗口,我个人更喜欢这个解决方案,在这个问题线程中提到过 JavaScript:位置。在新窗口/标签中打开Href ? < / p >
$(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();


});

例子工作。

你甚至可以用

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

如果弹出窗口被阻止,这将在同一选项卡上打开它。

我们必须动态地设置属性target="_blank"它会在新标签中打开。 document.getElementsByTagName("a")[0].setAttribute('target', '_blank') < / p >

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

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

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

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

不要在上面的例子中提供第二个参数_blank。

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