Recently, we are working on the encapsulation of real-time video, and the client needs Ajax to report status to the server in real time to confirm the current call status of the user. This involves sending offline status to the server when the user leaves the client (closes the browser).

Listen for browser closure events

There are two browser close events, UNLOAD and **beforunload. They are different. Literally, beforunload is called before unload.

Beforeunload fires when the user is about to leave the page and returns a string that the browser displays and queries to the user to determine whether to leave.

2. Unload is triggered when the user has already left. At this stage, we can only do some operations without delay.

3. Note that alert, confirm and prompt will be ignored if added to the two event listeners

4. Effective Status:

  • 1. Close the browser window
  • 2· When you go to other pages via the address bar or favorites
  • 3· Click back, Forward, Refresh, one of the home page
  • 4· When you click a link to a URL that goes to another page
  • 5· When any of the following events is called: The click,document.write() method (output content), document.open() opens a new blank document, and the document.close() method closes an output stream opened by the open() method and displays the selected data. , window close (), form.submit.
  • 6· When opening a page with Window Open and passing the name of the page’s window to the page to open.
  • 7. When the location. Href value is reassigned.
  • 8· Submit a form with the specified action via the Input Type = “submit” button.
  • 9. Can be used with the following elements: body, frameset, window

== code ==

window.onunload = function(){// related code} window.onbeforeunload =function(){// related code} window.adDeventListener ()'unload', ()=>{// related code}); window.addEventListener('beforeunload', ()=>{// related code});Copy the code

Sometimes two listeners need to work together, of course, to avoid repeated calls and do some processing.

Send a request

With the above two listeners in mind, let’s look at how the request can be successfully sent to the server. If you just write a request in the listener, the browser may stop the request before it is sent, and asynchronous Ajax may not reach the server accurately. Here are three ideas that can be implemented.

1. Request set to sync (not recommended)

Your first reaction might be to set the request to a synchronous request with the following code:

var xml = new XMLHttpRequest();

xml.open('POST', url , false); // falseXml.setrequestheader ("Content-type"."application/x-www-form-urlencoded");

xml.onreadystatechange = function() {
    if (xml.readyState == 4 && xml.status == 200) {
        var responeData = xml.responseText;
        var data = JSON.parse(responeData);
    } else{// handle exceptions}}; xml.send('account=1&password=123456');

Copy the code

This method can be implemented, but it will have a relatively large impact on the user experience, and in the latest HTTP protocol proposal, it is considered to remove the request synchronization standard

2. Use sendBeacon in Navigator to send asynchronous requests (recommended)

Related usage methods

body = JSON.stringify(body); // xhr.send(body) becomes navigator.sendbeacon (url,body);Copy the code

The supported body can be ArrayBufferView, Blob, DOMString, or FormData. According to MDN:

Primarily used for statistical and diagnostic code that typically tries to send data to a Web server before unloading a document. Sending data too early may result in missed data collection opportunities. However, it has been difficult for developers to ensure that data is sent during document uninstallation. Because the user agent usually ignores the asynchronous XMLHttpRequest generated in the unload event handler.Copy the code

Here are two other different types of sending

  • (1) Body uses Blob objects. One advantage is that you can customize the header
blob = new Blob([`accoutn=12332323`], {type : 'application/x-www-form-urlencoded'});
navigator.sendBeacon("/leave", blob);

Copy the code
  • (2) Use FormData, but the content-Type is automatically changed to “multipart/form-data”.
var fd = new FormData();
fd.append('account', 123);
navigator.sendBeacon("/leave", fd);
Copy the code

3, the server to receive

=-= Closing: By combining the above two methods, you can send the Ajax request at the end of the page =-=

Related links: juejin.cn/post/684490…