你可以使用以下类似的方法:
<!-- HTML -->
<a id="opener">Open window</a>
var a = document.getElementById('opener'), w;
a.onclick = function() {
if (!w || w.closed) {
w = window.open("https://www.google.com","_blank","menubar = 0, scrollbars = 0");
} else {
console.log('window is already opened');
}
w.focus();
};
这里是可工作的 jsBin | 更多关于 Window.open 方法的信息
如果您想要控制多个窗口,请使用下面的代码片段
<!-- HTML -->
<a href="https://www.google.com" class="opener">Open google.com</a> |
<a href="http://www.yahoo.com" class="opener">Open yahoo.com</a>
window.onload = function(){
var a = document.querySelectorAll('.opener'), w = [], url, random, i;
for(i = 0; i < a.length; i++){
(function(i){
a[i].onclick = function(e) {
if (!w[i] || w[i].closed) {
url = this.href;
random = Math.floor((Math.random() * 100) + 1);
w[i] = window.open(url, "_blank", random, "menubar = 0, scrollbars = 0");
} else {
console.log('window ' + url + ' is already opened');
}
e.preventDefault();
w[i].focus();
};
})(i);
}
};
这里是可工作的 jsBin
如果您不想让它们在单独的窗口中加载,只需排除此行即可。
random = Math.floor((Math.random()*100)+1);
并从下一行中删除random
引用
w[i] = window.open(url, "_blank", random, "menubar=0,scrollbars=0");
顺带一提:如您所见,我们创建了两个带有第三方内容的窗口;您应该知道,无法从这些窗口中获取任何引用(指父级/打开者窗口)。
window.open()
返回ref
,您可以在打开窗口之前检查它。var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);
- Girish