You can send a request when a page is closed, that won't get interrupted because the page is closing. The Fetch API allows you to send such requests, but normally they get interrupted so they may not reach the server. To force the request to get sent, you can use the keepalive option, like this:

const url = "http://example.com/my/resource";
const data = {a: 1, b: 2}; // some data to be logged, such as usage statistics

const handler = () => fetch(url, {method: "POST", keepalive: true});

window.addEventListener("unload", handler);

Another way of doing this would be to use the Beacon API, which is designed specifically for this use case and gives you the sendBeacon method. However, this approach has some restrictions:

  1. You can only do POST requests.
  2. The only HTTP header you can send is Content-Type.
const url = "http://example.com/my/resource";
const data = {a: 1, b: 2}; // some data to be logged, such as usage statistics

const blob = new Blob([JSON.stringify(data)], {type: "application/json"});
const handler = () => navigator.sendBeacon(url, blob);

window.addEventListener("unload", handler);
Previous on JavaScript
Mastodon Mastodon