SoFunction
Updated on 2025-04-07

The problem of sending a request without interruption is to fall back or close the vue page.

The vue page falls back or closes, and the sending request is not interrupted

I have a need to do a project recently

videoWhile 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.

firstvueCall a method before rolling back or closing the page

mounted() {
  ('beforeunload', e => (e))
},
destroyed() {
  ('beforeunload', e => (e))
}
  • mountedComponent mount life cycle LetwindowmonitorbeforeunloadEvents and give corresponding methods.
  • destroyedDestroy life cycle LetwindowRemove monitoringbeforeunloadevent.

exist pauseIn 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),axiosThe interface was interrupted and the call was not successful.

Searching for problems requires synchronous call to interfaces. Later useasync awaitCallaxios

Even use nativeXMLHttpRequestThe object calls the interface synchronously, and all ended in failure.

turn out to beChromeThe browser does not allow synchronous calls during page closingXMLHTTPRequest()Method, this rule applies tobeforeunloadunloadpagehideandvisibilitychangeTheseAPI

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-aliveAs 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
  });
}
  • fetchThe method does not require installation dependencies.vueUse directly in
  • WillkeepaliveSet astrueThis ensures that the browser is closed or fallback, the link to the calling interface will not be closed, and the call is successful.

Summarize