js实现关闭当前页面

时间:2021-01-23 19:15:29
当页面首次打开时,浏览器认为是不安全的并不能直接关闭当前窗口。这不是bug,有解释的链接:
https://*.com/questions/25937212/window-close-doesnt-work-scripts-may-close-only-the-windows-that-were-opene
https://*.com/questions/19761241/window-close-and-self-close-do-not-close-the-window-in-chrome
只有当页面从别的页面打开时或者window.open()打开时,window.close()才起作用
不同的浏览器有不用的兼容问题
代码如下:
if (navigator.userAgent.indexOf('MSIE') > 0) { // close IE
   if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
      window.opener = null;
      window.close();
   } else {
      window.open('', '_top');
      window.top.close();
   }
} else { // close chrome;It is effective when it is only one.
   window.opener = null;
   window.open('', '_self');
   window.close();
}