最好使用target="_blank"。
例如。在 Chrome 中,带有target="_blank" 的锚点会打开一个新标签,但是,window.open 会打开一个全新的窗口。
我尝试了一些实验来将window.open 替换为target="_blank"。
被弹出窗口拦截器阻止
// create an anchor, add to body, trigger click
var a = document.createElement('a');
a.setAttribute('href', 'http://google.com');
a.setAttribute('target', '_blank');
document.body.appendChild(a);
a.click();
// hijack first anchor, change href, trigger click
var a = document.getElementsByTagName('a')[0];
a.setAttribute('href', 'http://google.com');
a.setAttribute('target', '_blank');
a.click();
// hijack first anchor that has target=_blank, change href, trigger click
var a = $('a[target="_blank"]')[0];
a.setAttribute('href', 'http://google.com');
a.click();
弹出窗口拦截器允许
// hijack first anchor that has target=_blank, change href, next document click triggers it
var a = $('a[target="_blank"]')[0];
a.setAttribute('href', 'http://google.com');
$(document).click(function(){
$('a[target="_blank"]')[0].click();
});
// create an anchor, add to body, next document click triggers it
var a = document.createElement('a');
a.setAttribute('href', 'http://google.com');
a.setAttribute('target', '_blank');
document.body.appendChild(a);
$(document).click(function(){
a.click();
});
似乎只要弹出窗口是由用户交互触发的,弹出窗口拦截器就允许它。
Mozilla 在window.open 上的文档:
https://developer.mozilla.org/en-US/docs/Web/API/window.open