zoukankan      html  css  js  c++  java
  • window.close关闭当前页面

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

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

    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,再按照上述思路解决问题。

     

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

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

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

    var xx = navigator.userAgent.indexOf("Firefox") > -1 ? 
        function(){location.href = "about:blank";}
        :
        function(){
            window.opener = null;
            window.open("", "_self", "");
            window.close();
        };
  • 相关阅读:
    redis运维的一些知识点
    nginx 实现Web应用程序的负载均衡
    JQuery中常用方法备忘
    高效程序猿之 VS2010快速生成代码模板
    C# var 隐式类型 var 用法 特点
    HTML之打开/另存为/打印/刷新/查看原文件等按钮的代码
    js函数大全(2)
    js常用函数大全107个
    js键盘键值大全
    js键盘键值大全
  • 原文地址:https://www.cnblogs.com/mr189/p/3700325.html
Copyright © 2011-2022 走看看