新标签中的javascript window.location


123

我将用户引导至某些URL,window.location但该URL在浏览器的同一选项卡中打开。我希望它在新标签页中打开。我可以使用window.location吗?还有另一种方法可以执行此操作吗?



window.location一个要求?还是可以提供其他JS解决方案?
Khez 2011年

@Khez:可以提供其他JS。
穆罕默德·伊姆兰·塔里克

Answers:


27

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


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

第二个参数是使其在新窗口中打开的原因。不要忘记阅读Jakob Nielsen的翔实文章 :)


10
但是,如果您的浏览器阻止了弹出窗口上的设置,该怎么办?这不会炒锅。
pregmatch

@Alex meh ...不是真正的“正确”答案。在阻止弹出窗口的Firefox中尝试此代码失败。
塔库斯

14

这对我在Chrome 53上有效。在其他任何地方都未进行测试:

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

6

使用jQuery甚至更容易,并且可以在Chrome上运行

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


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.