项目场景:
需求:用户手动关闭浏览器需要提示,但是代码自动触发的关闭不提示
逻辑实现
mounted() {
window.addEventListener('beforeunload', e => this.beforeunloadHandler(e));
},
destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e));
},
methods: {
beforeunloadHandler(e) {
if (this.$route.name == 'learn_plan_exam' && this.showCloseTip) {
e = e || window.event;
// 兼容IE8和Firefox 4之前的版本
if (e) {
e.returnValue = '关闭提示';
}
// Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
return '关闭提示';
} else {
window.onbeforeunload = null;
}
},
}
showCloseTip: 是控制需不需要弹框的值
问题:
测试说:他关闭时 没有任何提示
解决方案:
经过多次验证我发现 代码逻辑并没有问题,出现这个问题的原因是:
1、在IE中这个事件只要去关闭窗口就触发。
2、谷歌、火狐等在F12调试模式中也会起效
3、谷歌、火狐、edge等浏览器中被优化了,需要用户在页面有过任何操作才会出现提示!
注意第三点 一定要用户在自己的页面进行过操作,事件才会生效。。。