brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: navigator.sendBeacon() sends a last bit of data when a visitor leaves

Web-Development
~/tips/tip-javascript-navigator-sendbeacon

const data = JSON.stringify({ path: location.pathname, seconds: timeOnPage });

Sends a small POST request reliably when a visitor leaves or hides the page.

If you run your own small analytics or want to save a draft when someone closes a tab, the moment they leave is the worst moment to send a request. The browser is busy unloading the page and may simply drop a normal fetch(). navigator.sendBeacon() was made for exactly this, and I like how little code it takes.

It queues a small POST request that the browser sends in the background, even after the page is gone, without making the next page wait. MDN’s recommended way to call it is on the visibilitychange event:

document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden") {
    const data = JSON.stringify({ path: location.pathname, seconds: timeOnPage });
    navigator.sendBeacon("/log", data);
  }
});

The data can be a string, a Blob, FormData, URLSearchParams or a buffer. It returns true when the browser has queued the request, which says nothing about whether the server got it.

Why visibilitychange and not unload or beforeunload? MDN is blunt about it: on phones those events often don’t fire at all, for example when someone switches to another app and later swipes the browser away. An unload handler can also keep a page out of the back/forward cache in Firefox, which makes the back button slower. pagehide is better for the cache, but has the same reliability problem.

The caveats are the limits. The request is always a POST, you can’t set custom headers and you never see the response. The queued data is limited to 64 KiB in total, so it’s for a small summary, not a file upload. When you need another method or the response, MDN points to fetch() with keepalive: true. Also keep in mind that visibilitychange fires every time the tab goes to the background, so the same visitor can send several beacons. Make your server fine with that.

Support has been there for years: Chrome 39, Firefox 31 and Safari 11.1, Baseline widely available since 2020.

Further reading: MDN: Navigator.sendBeacon(), MDN: visibilitychange event

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link