Think of the page as going through states (visible, hidden, frozen, gone) rather than as getting one "goodbye" event.
visibilitychange(ondocument) fires wheneverdocument.visibilityStateflips between"visible"and"hidden": tab switches, minimising, locking the phone, and also navigating away and closing. Chrome's lifecycle docs call"hidden"often the last state change you can observe, especially on mobile, where the OS can kill a backgrounded browser without firingbeforeunload,pagehideorunload. Save drafts and flush analytics here; the page may also come back, so make it repeatable.pagehidefires when the page is being left: navigation, reload or close, but not a tab switch.event.persistedistrueif it may enter the back/forward cache, so don't treat it as the end.beforeunloadexists for one job: asking "leave with unsaved changes?". Callevent.preventDefault()(or setreturnValueto a non-empty string). Browsers show their own text, never yours, and only if the user has interacted with the page. Add the listener only while there are unsaved changes.unloadfires last, only when the page won't be cached. It's often skipped on mobile, keeps the page out of the back/forward cache where it runs, and Chrome's docs say it stopped running by default in Chrome 155. Don't use it.freezeandresume(ondocument) come from the WICG Page Lifecycle draft and exist only in Chromium. Chrome's docs say it freezes hidden pages to save resources; Chrome 156 also firedfreezewhen a page entered the back/forward cache. After a discarded tab is reloaded,document.wasDiscardedistrue.
On navigation, the HTML order is beforeunload, pagehide, visibilitychange to "hidden", then unload.