新选项卡中的 javascript window.location
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7554108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript window.location in new tab
提问by Muhammad Imran Tariq
I am diverting user to some url through window.location
but this url opens in the same tab in browser. I want it to be open in new tab. Can I do so with window.location? Is there another way to do this action?
我正在将用户转移到某个网址,window.location
但此网址在浏览器的同一选项卡中打开。我希望它在新标签中打开。我可以用 window.location 这样做吗?有没有其他方法可以执行此操作?
采纳答案by Ian Oxley
I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open
and hoping that the user has their browser set to open new windows in new tabs.
我认为没有办法做到这一点,除非您正在编写浏览器扩展程序。您可以尝试使用window.open
并希望用户将浏览器设置为在新选项卡中打开新窗口。
回答by
window.open('https://support.wwf.org.uk', '_blank');
The second parameter is what makes it open in a new window. Don't forget to read Jakob Nielsen's informative article:)
第二个参数是使它在新窗口中打开的原因。不要忘记阅读Jakob Nielsen 的内容丰富的文章:)
回答by rodrigo-silveira
This works for me on Chrome 53. Haven't tested anywhere else:
这在 Chrome 53 上对我有用。没有在其他地方测试过:
function navigate(href, newTab) {
var a = document.createElement('a');
a.href = href;
if (newTab) {
a.setAttribute('target', '_blank');
}
a.click();
}
回答by relief.melone
with jQuery its even easier and works on Chrome as well
使用 jQuery 更简单,也可以在 Chrome 上使用
$('#your-button').on('click', function(){
$('<a href="https://www.some-page.com" target="blank"></a>')[0].click();
})
回答by Fanis Mahmalat
You can even use
你甚至可以使用
window.open('https://support.wwf.org.uk', "_blank") || window.location.replace('https://support.wwf.org.uk');
This will open it on the same tab if the pop-up is blocked.
如果弹出窗口被阻止,这将在同一选项卡上打开它。
回答by OyeHarish
Rather going for pop up,I personally liked this solution, mentioned on this Question thread JavaScript: location.href to open in new window/tab?
而不是弹出,我个人喜欢这个解决方案,在这个问题线程JavaScript: location.href to open in new window/tab 中提到过 ?
$(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();
});
Working example.
工作示例。