I need to capture the window.onbeforeunload event

无人久伴 提交于 2021-01-01 18:37:01

问题


I am working on a project where I need to capture the browser close event (unload or beforeunload). For that I have tried the code below but it's not working.

The code is working only if I open the browser console window (maybe just for a second) but it is required otherwise it's not working.

Example

$(window).on('beforeunload', function(e) {
 $.ajax({
    type: "POST",
    url: "url",
    data : {'value' : 1},
    dataType:'json'
 });
  return false;   
});

回答1:


The beacon API is meant specifically for that. Sending a request as the page is unloading. https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API

Beacon requests use the HTTP POST method and requests typically do not require a response. Requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example XMLHttpRequest).

window.onunload = function analytics(event) {
  if (!navigator.sendBeacon) return;

  var url = "https://example.com/analytics";
  // Create the data to send
  var data = "state=" + event.type + "&location=" + location.href;

  // Send the beacon
  var status = navigator.sendBeacon(url, data);

  // Log the data and result
  console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status);
};


来源:https://stackoverflow.com/questions/58732391/i-need-to-capture-the-window-onbeforeunload-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!