运用的知识点:JavaScript的 onbeforeunload 函数

使用方法

window.οnbefοreunlοad=function(){

  return ‘’;

}

注意:有返回值(' ',true,false...都可以)才能弹出显示,或者有需要执行的事件也行。

 

onload、onunload、onbeforeunload的执行问题:

        页面加载时只执行onload

        页面关闭时,先onbeforeunload事件,再onunload事件。

        页面刷新时先执行onbeforeunload,然后onunload,最后onload。

        注意:这种执行顺序是有浏览器的兼容问题的,请注意各种浏览器的区别。

 

onbeforeunload() 和onunload() 两个事件的区别:

        相同点:

                两者都是在对页面的关闭或刷新事件作个操作。

        不同点:

                onbeforeunload()事件执行的顺序在onunload()事件之前发生。(因为,onbeforeunload()是在页面刷新之前触发的事件,而onubload()是在页面关闭之后才会触发的)。

                onbeforeunload()事件可以禁止onunload()事件的触发。

                onunload()事件是无法阻止页面关闭的。

                浏览器的兼容性不同。


 

vue中监听页面刷新和离开

方法一:直接在mounted或者activated中写

mounted() {        //写在mounted或者activated生命周期内即可
    window.onbeforeunload = e => {      //刷新时弹出提示
        return ''
    };
},

兼容性更好的写法:

window.onbeforeunload = function (e) {
  e = e || window.event;

  // 兼容IE8和Firefox 4之前的版本
  if (e) {
    e.returnValue = '关闭提示';
  }

  // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
  return '关闭提示';
};

方法二:添加监听

1. 在methods生命周期钩子中定义事件

methods: {
    beforeunloadFn (e) {
        // ...
    }
}

2.在 mounted 或者 activated 钩子中注册事件

mounted() {
    window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
}

3. 在 destroyed 钩子卸载事件

destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
}

 

参考文章:https://www.jb51.net/article/102461.htm

                  https://www.cnblogs.com/gavin0517/p/5827405.html

                  https://blog.csdn.net/tayshin/article/details/73770653

 

文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!

对博客文章的参考,若原文章博主介意,请联系删除!请原谅

                  

 

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐