Requirement: Send interface when closing browser, clear data, need to use the events [beforeunload] and [unload]. Note the following: [beforeunload] : Fires both when refreshing and closing [unload] : Fires while uninstalling 1. Interface interaction is invalid for security (window.open, alert, confirm etc.). 2. Request the interface synchronously to ensure that the page is closed after the interface request is completed, or use the fetch with an attribute [Keepalive: true].

// In Mounted listen for event window.addEventListener('beforeunload', e => this.beforeunloadHandler(e)) window.addEventListener('unload', e => this.unloadHandler(e))Copy the code
/ / remove the event window in the destroyed. The removeEventListener (' beforeunload ', e => this.beforeunloadHandler(e)) window.removeEventListener('unload', e => this.unloadHandler(e))Copy the code
beforeunloadHandler () { this.beforeUnloadTime = new Date().getTime() }, UnloadHandler () {const gapTime = new Date().getTime() - this.beforeunloadTime // Differentiates whether the browser is refreshed or closed if (gapTime <= 5) {const  url = `url` fetch(url, { headers: { 'X-Access-Token': token, 'content-type': 'application/json; charset=UTF-8' }, method: 'DELETE', keepalive: true }) } }Copy the code