Sunil Bamal
Sunil Bamal

Reputation: 117

I need to capture the window.onbeforeunload event

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;   
});

Upvotes: 1

Views: 2371

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

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);
};

Upvotes: 3

Related Questions