vue项目使用js监听浏览器关闭、刷新、后退事件

一、业务场景:

在项目的某些页面中,在执行某些接口调用过程的时候,如果用户选择刷新、关闭或者后退浏览器。有可能会造成接口被阻断,所以可能你会需要js监听浏览器关闭、刷新、后退事件,在进行这些操作的时候给个提示。如下图:
在这里插入图片描述
在这里插入图片描述

二、实现方式

1、监听浏览器关闭、刷新,给出提示

methods: {
       handleBeforeUnload(event) {
            // 兼容火狐的做法
            event.preventDefault()
            event.returnValue = ''
            // 展示提示消息 
            // (这里其实修改默认提示语是不生效的,不过我的业务场景不需要修改默认提示语
            // 我也没找到能修改的方法,有大佬知道的话麻烦告知)
            const message = '确定要离开吗?'
            event.returnValue = message
            return message
        }
},
 mounted() {
        window.addEventListener('beforeunload', this.handleBeforeUnload)
        window.addEventListener('unload', this.handleBeforeUnload)
    },
    destroyed() {
        window.removeEventListener('beforeunload', this.handleBeforeUnload)
        window.removeEventListener('unload', this.handleBeforeUnload)
    },

2、监听浏览器后退,给出提示

methods:{
      onPopState(e) {
                // 监听到浏览器回退事件(这里提示用的confirm,是可以自定义的)
                if (confirm('离开当前页面数据可能会丢失,您确定离开当前页面吗?')) {
                    // 点击确定回退
                    window.removeEventListener('popstate', this.onPopState)
                    window.history.go(-1)
                } else {
                    // 点击取消不回退
                    window.history.pushState(null, null, window.location.href)
                }
        },
      },
     mounted() {
	        // 添加 popstate 事件监听
	        window.history.pushState(null, null, window.location.href);
	        window.addEventListener('popstate', this.onPopState);
       },
    beforeDestroy() {
        // 在组件销毁前,移除 popstate 事件监听
        window.removeEventListener('popstate', this.onPopState)
    }

end~

猜你喜欢

转载自blog.csdn.net/weixin_52443895/article/details/130999729