Technical

pagehide

Also called page hide event.

pagehide is the browser event fired when a page is being unloaded or moved into the back/forward cache. It is the reliable last chance to send data before the visitor is gone, especially on mobile.

How it is measured

Attach a listener with `addEventListener('pagehide', ...)`. The event has a `persisted` flag: true means the page is entering the back/forward cache and may return, false means it is being discarded. Check by navigating away, pressing Back, and logging both events.

Unlike `unload`, pagehide fires on mobile Safari and does not disable the cache. Count how often your final beacon arrives against the number of page loads.

Worked example

A docs site sends time on page from an `unload` handler. On iPhones only 41 of 100 test visits deliver it. After moving the beacon to `pagehide` with a `visibilitychange` backup, 93 of 100 arrive, and the site stops being excluded from the back/forward cache.

With `persisted: true` the same page can be shown again on Back, so the team resets its timers on `pageshow` to avoid counting the hidden time.

How it differs

pagehide fires when the page is leaving. Visibility state reports whether the page is on screen right now, and `visibilitychange` fires on tab switches even when the visitor comes back. pagehide ends a page's life, while visibility state only describes what is visible.

Common errors

Using `unload` or `beforeunload`. Starting async work that will not finish. Assuming it fires on a crash or OS kill. Ignoring `persisted`. Sending twice, from pagehide and visibilitychange. Using synchronous XHR.

In practice

Send the final payload with `sendBeacon` on `visibilitychange` to hidden, use pagehide as a backup, and set a flag so it goes out once. Test on a real phone by swiping to the app switcher.

See also

Visibility state, sendBeacon, Engagement time

Sources

Count this on a real site.

Watch my website