一、业务场景:
在项目的某些页面中,在执行某些接口调用过程的时候,如果用户选择刷新、关闭或者后退浏览器。有可能会造成接口被阻断,所以可能你会需要js监听浏览器关闭、刷新、后退事件,在进行这些操作的时候给个提示。如下图:文章来源:https://www.toymoban.com/news/detail-564492.html
二、实现方式
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~文章来源地址https://www.toymoban.com/news/detail-564492.html
到了这里,关于vue项目使用js监听浏览器关闭、刷新、后退事件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!