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();
    };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM