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)
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值