The vue project uses js to monitor browser close, refresh, and back events

1. Business scenario:

In some pages of the project, when executing some interface calling process, if the user chooses to refresh, close or back the browser. It may cause the interface to be blocked, so you may need js to monitor the browser close, refresh, and back events, and give a reminder when performing these operations. As shown below:
insert image description here
insert image description here

2. Implementation method

1. Monitor the closing and refreshing of the browser, and give a prompt

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. Listen to the browser back and give a prompt

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~

Guess you like

Origin blog.csdn.net/weixin_52443895/article/details/130999729