The HTML onpagehide attribute is an event handler that triggers a script to execute when the user navigates away from a webpage.
Definition and Usage
➔ It is mainly used in the <body> element or Window object.
➔ This onpagehide event is often preferred over the older onunload event because, unlike onunload, onpagehide does not prevent the browser from caching the page. This provides a fast "back" navigation experience for the user.
➔ persisted is a boolean property that indicates whether the page is being cached (true) or completely unloaded (false).
The onpagehide event can be fired in a variety of situations, such as:
- Clicking on a link to a different page.
- A form is being submitted.
- Refresh the browser window.
- Closing the browser window or tab.
Syntax
//In HTML
<body onpagehide="myFunction()"></body>
//In Javascript
window.addEventListener('pagehide', function(event) {
// JavaScript code when the page is hidden
if (event.persisted) {
// code if cached
} else {
// code goes here
}
});