JavaScript关闭当前页

出于安全考虑,普通页面直接执行window.close()时不会生效,控制台会出现如下警告:

1
Scripts may not close windows that were not opened by script.

只有那些通a标签或者window.open()打开的页面才支持关闭,为什么这么规定呢?可能是直接输入地址访问的页面可能比较重要,减少被恶意JS攻击的可能性吧,所以规定只有用脚本(或代码)打开的页面才能用脚本关闭。

IE和火狐还未测试,Chrome已没问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 关闭页面
closeCurrentPage() {
const ua = window.navigator.userAgent;
if (ua.indexOf('MSIE') > 0) {
if (ua.indexOf('MSIE 6.0') > 0) {
window.opener = null;
window.close();
} else {
window.open('', '_top');
window.top.close();
}
} else {
window.opener = null;
window.open('', '_self', '');
window.close();
}
}

还有种方法通过a标签的方式去操作

1
<a href="javascript:window.close()">关闭</a>