window.close closes the current page

Browsers are under security policy considerations, and only allow Javascript to close pages opened by javascript. In order to close the current window with js, we can consider this way. This is also the most common practice.

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

The original foreigner's explanation on 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).

Another solution is also attached:

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

 The embedded javascript: window.open("", "_self", ""); is to prevent IE from popping up a confirmation close box, which is equivalent to resetting window.opener

FireFox has built-in support for window.close, but due to its own settings, JS is not allowed to close windows by itself, so users need to manually modify the value of dom.allow_scripts_to_close_windows under about:config to true, and then solve the problem according to the above ideas.

 

In many cases, users will not manually modify the FireFox settings. There is also a compromise method. Changing the behavior of "close" to "location.href" jumps only for FireFox.

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

In summary, the JS part can be modified as follows:

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

Guess you like

Origin blog.csdn.net/AN0692/article/details/105832124