Three ways to leave the page to realize the monitoring browser:
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 = 'Do you confirm to leave this page-the data you enter may not be saved'
}
this.cancelfunc ()
}
},
async Cancethcunc () {
const params = {
name: 'AA',
_csrf: SessionStorage._csrf
}
await this.Cancelorder (params)
},
async cancelorder (params) {
const response = await api.Cancelordrapi (params) // Request background interface
console.log ('synchronous request', response.data)
},
navigator.sendBeacon()
description
This method is mainly used to meet the needs of statistics and diagnostic codes. These code usually sends data to the web server before uninstalling (UNLOAD) document.
grammar
navigator.sendBeacon(url, data);
parameter
- URL indicates the network address to be sent to.
The
- Data parameter is the data of ArrayBufferView or Blob, DomString or FormData types to be sent.
return value
When the user agent successfully adds the data to the transmission queue, the SendBeacon () method will return True, otherwise False will be returned.
implementation
Since there is an interface, it is simple to implement.
Window.addeventListener ("Beforeunload", (E) => {
const data = {name: "Xiaomi"};
window.navigator.sendbeacon ("http://127.0.0.0.1:1991/loginout", json.stringify (data);
});
Effect
Whether it is refreshing the page or closing the page, the background can receive the request sent from the front end, perfectly implementing the demand.
Method 2 Reference article: https://juejin.cn/post/6997016317635084319