Window: pagehide event
The pagehide
event is sent to a Window
when the browser hides the current page in the process of presenting a different page from the session's history.
For example, when the user clicks the browser's Back button, the current page receives a pagehide
event before the previous page is shown.
Bubbles | No |
---|---|
Cancelable | No |
Interface | PageTransitionEvent |
Event handler property | onpagehide |
Usage notes
Like the unload
and beforeunload
events, this event is not reliably fired by browsers, especially on mobile. For example, the pagehide
event is not fired at all in the following scenario:
- A mobile user visits your page.
- The user then switches to a different app.
- Later, the user closes the browser from the app manager.
However, unlike the unload
and beforeunload
events, this event is compatible with the back/forward cache (bfcache), so adding a listener to this event will not prevent the page from being included in the bfcache.
The best event to use to signal the end of a user's session is the visibilitychange
event. In browsers that don't support visibilitychange
the pagehide
event is the next-best alternative.
If you're specifically trying to detect page unload events, the pagehide
event is the best option.
See the Page Lifecycle API guide for more information about how this event relates to other events in the page lifecycle.
Examples
In this example, an event handler is established to watch for pagehide
events and to perform special handling if the page is being persisted for possible reuse.
window.addEventListener("pagehide", event => { if (event.persisted) { /* the page isn't being discarded, so it can be reused later */ } }, false);
This can also be written using the onpagehide
event handler property on the Window
:
window.onpagehide = event => { if (event.persisted) { /* the page isn't being discarded, so it can be reused later */ } }
Specifications
Specification |
---|
HTML Standard (HTML) # event-pagehide |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
pagehide_event |
3 |
12 |
Yes |
Yes |
Yes |
Yes |
≤37 |
18 |
Yes |
Yes |
Yes |
1.0 |
See also
- The
pageshow
event. - Page Lifecycle API gives best-practices guidance on handling page lifecyle behavior in your web applications.
- PageLifecycle.js: a JavaScript library that deals with cross-browser inconsistencies in page lifecyle behavior.
- Back/forward cache explains what the back/forward cache is, and its implications for various page lifecycle events.
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event