onunloadsendbeacon

navigator.sendBeacon not called from unload


According to MDN and the specs, navigator.sendBeacon is intended to be called from window unload. Now, it does not seem to work anymore if you close the last tab of your browser, or your entire browser window.

Can anyone confirm if this is by design? If so, is there a workaround to send lastminute data on unload?

I tested with this sample file, in Firefox 74 and Chrome 81, looking for calls with Fiddler.

<html>
<head>
<title>unload test page</title>
<script>
window.addEventListener("unload", function () {
  navigator.sendBeacon('https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon');
});
</script>   
</head>
<body>
    <p><div>unload test page</div></p>
</body>
</html>

Solution

  • MDN states (as of 1/12/2021):

    It’s intended to be used in combination with the visibilitychange event (but not with the unload and beforeunload events)

    When visibilitychange transitions to hidden, you can treat that as when the tab/browser is closing and use sendBeacon then.

    Example code from MDN:

    document.addEventListener('visibilitychange', function logData() {
      if (document.visibilityState === 'hidden') {
        navigator.sendBeacon('/log', analyticsData);
      }
    });