The vue page falls back or closes, and the sending request is not interrupted
I have a need to do a project recently
video
While playing the video, click on the browserRetraceButtonCalling the interfaceStatistics the viewing time.
It was this seemingly simple thing that I had torn for two days and finally got it done.
firstvue
Call a method before rolling back or closing the page
mounted() { ('beforeunload', e => (e)) }, destroyed() { ('beforeunload', e => (e)) }
-
mounted
Component mount life cycle Letwindow
monitorbeforeunload
Events and give corresponding methods. -
destroyed
Destroy life cycle Letwindow
Remove monitoringbeforeunload
event.
exist pause
In the method, the interface is called to count the video viewing time.
The problem arose at this time
After the browser falls back (or closes),axios
The interface was interrupted and the call was not successful.
Searching for problems requires synchronous call to interfaces. Later useasync await
Callaxios
。
Even use nativeXMLHttpRequest
The object calls the interface synchronously, and all ended in failure.
turn out to beChrome
The browser does not allow synchronous calls during page closingXMLHTTPRequest()
Method, this rule applies tobeforeunload
、unload
、pagehide
andvisibilitychange
TheseAPI
。
In order to ensure that the page can successfully call the interface to request data during uninstallation, the official suggests that you usesendBeacon()
orFetch keep-alive
。
byFetch keep-alive
As an example:
pause() { let url = .VUE_APP_BASE_URL + '/api/setData'; let data = { ...params // Some parameters } // fetch calls the interface fetch( url, { method: 'POST', headers:{ 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + getToken() // getToken Return token }, body: (data), keepalive: true }); }
-
fetch
The method does not require installation dependencies.vue
Use directly in - Will
keepalive
Set astrue
This ensures that the browser is closed or fallback, the link to the calling interface will not be closed, and the call is successful.