Application of Beacon API – to call a request provided by the backend before the browser is closed

I encountered a requirement that a request provided by the backend should be called before the browser is closed. I used axios at first, and I swore that there was no problem. The backend later told me that no request was received. At this time, I I went to rule out the reason. I looked at the debugger. It was obvious that a request was sent, but it was still pending when unloaded. Guess if the request was interrupted. Trying to use synchronous request is still useless, then all I can think of is to use native http synchronous request, but the shortcomings are also obvious, and the performance is poor. So I was puzzled and finally found an api on mdn

 window.addEventListener("unload", function() { let ISEdit = sessionStorage.getItem("isCanEdit") == "true" ? true : false; if (ISEdit) { let params = new FormData(); params.append("patientContentId", self.getquestionId); navigator.sendBeacon( `${config.baseurl}/patient/deleteExclusive`, params ); ; } });

To cooperate with the backend, you need a post request and change it to formdata, and you’re done.

Question & Solution

The Beacon API does not delay page unloading and does not seriously affect the user experience.

In order to solve the problem that the asynchronous request cannot be successful when the webpage is unloaded, the browser specially implements a…

The post Beacon API Application – Requests to call a backend before the browser is closed first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9391
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment