window.close关闭当前页面

时间:2014-07-22 23:09:52   收藏:0   阅读:575

浏览器处于安全策略考虑,只允许Javascript关闭由javascript打开的页面,为了用js关闭当前窗口,我们可以这么考虑,这也是最常用的做法。

<a href="javascript:;" onclick=‘xx()‘>fdsafas</a>
mamicode.com,码迷
function xx(){
    // 重置window.opener用来获取打开当前窗口的窗口引用
  // 这里置为null,避免IE下弹出关闭页面确认框
    window.opener = null;
    // JS重写当前页面
    window.open("", "_self", "");
    // 顺理成章的关闭当前被重写的窗口
    window.close();
}
mamicode.com,码迷

stackoverflow上老外的原文解释:

For security reasons, a window can only be closed in JavaScript if it was opened by JavaScript. In order to close the window, you must open a new window with _self as the target, which will overwrite your current window, and then close that one (which you can do since it was opened via JavaScript).

也附上另外一种解决思路:

window.open(‘javascript:window.open("", "_self", "");window.close();‘, ‘_self‘);

 内嵌的javascript:window.open("", "_self", "");是为了防止IE弹出确认关闭框,等于重置window.opener

FireFox内置支持window.close,但是由于本身的设定,不允许JS自行关闭窗口,所以需要用户手动修改about:config下的dom.allow_scripts_to_close_windows的值为true,再按照上述思路解决问题。

 mamicode.com,码迷

很多情况下用户不会手动去修改FireFox的设置,这里也有个折中的办法,在将"close"的行为变化为"location.href"跳转,仅针对FireFox

function xx(){
    location.href = "about:blank";
}

 

综上,JS部分可以修改如下:

mamicode.com,码迷
var xx = navigator.userAgent.indexOf("Firefox") > -1 ? 
    function(){location.href = "about:blank";}
    :
    function(){
        window.opener = null;
        window.open("", "_self", "");
        window.close();
    };
mamicode.com,码迷

 

window.close关闭当前页面,码迷,mamicode.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!