This is the 13th day of my participation in the August More Text Challenge

Demand scenarios

  1. Send requests before the user leaves the page, and perform data reporting (such as counting the duration of the user’s stay)
  2. Edit interface does not save exit case, save data for recovery

Not recommended

1. Inunload / beforeunloadTo send a synchronization request

※ Neither How AXIos nor FETCH supports synchronous requests, so native AJAX is required.

sync_test() {
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function(){ 
		/ /...
	}
	xhr.open("GET"."http://xxx/xxx".false);
	xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");
	xhr.send(null)}window.onbeforeunload = function(e) {
  sync_test() // Send a synchronization request
}
Copy the code

Does the ResultError:Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://xxxx/': Synchronous XHR in page dismissal. Does according toChrome does not support sending synchronization requests during page unload events (unload, beforeUnload).

Ajax Synchronous Request Failing in Chrome www.jackpu.com/jie-jue-syn…

※ More sends synchronization requests using UNLOAD/BrforeUnload. Chrome versions 73 and 74 are supported (as are other browsers). Even so, using synchronous XMLHttpRequest is not recommended because it delays page unloading and affects the loading of the next navigation, which is not user friendly.

In 2.unload / beforeunloadCreate a picture

Delay unload by creating an image element in UNLOAD/BRforeUnload and setting its SRC attribute to ensure data is delivered. This approach is also not recommended: not only is the encoding pattern bad, it also results in very poor page loading performance.

Recommended scheme

Use the navigator. SendBeacon. Using this method to send a request ensures that the data is delivered effectively and does not block the load or unload of the page.

Does How

window.onbeforeunload = function(e) {
  navigator.sendBeacon(url, data)
}
Copy the code

※ More sendBeacon processing result? SendBeacon returns true if it successfully enters the browser send queue. Return false if constrained by the total number of queues and data size. If you return true, you are in the send queue, and the browser will do its best to ensure that the send succeeds, but there will be no return value.

The Beacon API is used to send small amounts of data to the server without waiting for a response. Beacons are designed to send data and then forget about it. We didn’t expect a response, and we won’t get one. Use the Web Beacon API to record activity


Reference links:

www.jianshu.com/p/04e88271a… (Recommended reading, written very clearly) qnimate.com/sending-dat… Developer.mozilla.org/zh-CN/docs/… www.cnblogs.com/yelongsan/p…