前端vue+axios实现关闭/刷新页面前向后台接口发送请求
created() {window.addEventListener('beforeunload', e => {this.updateHandler(e)})}destroyed() {window.removeEventListener('beforeunload', e => {this.updateHandler(e)})},beforeDestroy() {this.canc
·
实现监听浏览器三种离开页面的方式:
代码:
created() {
window.addEventListener('beforeunload', e => {
this.updateHandler(e)
})
}
destroyed() {
window.removeEventListener('beforeunload', e => {
this.updateHandler(e)
})
},
beforeDestroy() {
this.cancelFunc()
},
methods: {
updateHandler(e) {
e = e || window.event
if (e) {
e.returnValue = '您是否确认离开此页面-您输入的数据可能不会被保存'
}
this.cancelFunc()
}
},
async cancelFunc() {
const params = {
name: 'aa',
_csrf: sessionStorage._csrf
}
await this.cancelOrder(params)
},
async cancelOrder(params) {
const response = await API.cancelOrderAPI(params) // 请求后台接口
console.log('同步请求', response.data)
},
方法二:
navigator.sendBeacon()
描述
这个方法主要用于满足统计和诊断代码的需要,这些代码通常尝试在卸载(unload)文档之前向web服务器发送数据。
语法
navigator.sendBeacon(url, data);
参数
- url 表明 data 将要被发送到的网络地址。
- data 参数是将要发送的 ArrayBufferView 或 Blob 、DOMString 或者 FormData 类型的数据。
返回值
当用户代理成功把数据加入传输队列时,sendBeacon() 方法将会返回 true,否则返回 false。
实现
既然有了接口,那实现起来就简单了。
window.addEventListener("beforeunload", (e) => {
const data = {name: "小米"};
window.navigator.sendBeacon("http://127.0.0.1:1991/loginout", JSON.stringify(data));
});
效果
不管是刷新页面还是关闭页面,后台都能接收到前端发送过来的请求,完美实现需求。
方法二参考文章:https://juejin.cn/post/6997016317635084319
更多推荐
已为社区贡献39条内容
所有评论(0)