过去,当直接调用window对象的close()方法,而不是对window实例调用close()时,浏览器会关闭最前面的窗口,不管脚本是否创建了该窗口。现在,出于安全原因,不再允许脚本关闭未打开的窗口。(Firefox46.0.1:脚本无法关闭尚未打开的窗口)
1.直接调用window对象的close()方法
window.close()
当直接调用window.close()方法时,IE会弹出提示框,询问是否关闭此窗口。
Firefox则不会关闭页面。
Google则会立即关闭当前页面。
2.window实例调用close()方法
针对IE,去除提示框需要创建一个window实例,先打开该窗口,就可以直接关闭。
window.opener = null;
window.open('', '_self');
window.close();
针对FireFox,之所以window.close在firefox不能使用,是因为firefox默认不能关闭用户打开的网页。
利用在当前窗口中打开一个新窗口来替换当前打开的页面,然后关闭该窗口。其中window.open(‘about:blank’,’_self’)返回的是当前窗口的引用。
var opened=window.open('about:blank','_self');
opened.opener=null;
opened.close();
如果要关闭的页面有父页面,可以使用下面的方法
window.open('','_parent','');
window.close();
3.兼容写法:
if(firefox) {
var opened=window.open('about:blank','_self');
opened.opener=null;
opened.close();
} else {
window.opener = null;
window.open('', '_self');
window.close();
}
最直接的办法是在FireFox浏览器中输入about:config,然后找到dom.allow_scripts_to_close_windows项,把false设为true,这样window.close()就可以使用了,FireFox默认状态window.close是无效的。但需要客户去设置,肯定不是开发者想要的。