Use navigator.sendBeacon to report data

For example, in some statistical systems, if you want to report the current data when the page is unloaded, the synchronous reporting method of xhr will block the jump of the current page; using new Image may encounter aborted, which will result in failure to send successfully.
 
Well, the browser can now use a more concise sendBeacon method that provides send guarantees. sendBeacon is asynchronous, does not affect the jump speed from the current page to the next page, and is not restricted by the same domain.
 
window.addEventListener('unload', logData, false);
 
function logData() {
navigator.sendBeacon("/log", analyticsData);
}
 
sendBeacon will return true if it successfully enters the browser's send queue; if it is limited by the total number of queues and data size, it will return false. After returning ture, it just means that it has entered the sending queue. The browser will try its best to ensure that the sending is successful, but whether it is successful or not, there will be no return value. There is currently no specific data length limit standard.
 
Considering the support for the current browser, it is necessary to do a downgrade support (such as xhr in synchronous mode, if it is not the same domain, it must support CORS):
 
navigator.sendBeacon || new Function('var xhr=new XMLHttpRequest();xhr.open("POST",arguments[0],true);r.send(arguments[1]);');
 
Current browser support for sendBeacon (see the latest progress: http://caniuse.com/#search=sendBeacon):
 
Chrome 37+
Firefox (Gecko) 31+
Internet Explorer does not support
Opera 24+
Safari does not support
Commonly used browsers on mobile phones are not supported: Android browsers are supported, but iOS is not yet supported
Google Analytics already uses navigator.sendBeacon() to report data: http://www.thyngster.com/google-analytics-added-sendbeacon-functionality-universal-analytics-javascript-api/
 
via:
W3 standard description: https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/Beacon/Overview.html
MDN introduction: https://developer.mozilla.org/en-US/docs/Web/API/navigator.sendBeacon
 
example:
function SendBeacon(src)
     if (typeof(navigator.sendBeacon) == "function") {
          var b = new Blob([], {type: 'application/x-www-form-urlencoded'});
          return navigator.sendBeacon(src, b);
     }
     return false;

 

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326350828&siteId=291194637