What is the usage of onpagehide event in JavaScript?

The onpagehide event triggers in JavaScript when a user leaves the page and navigates away. This occurs during page refresh, clicking links, closing the browser tab, or navigating to another page.

Syntax

// HTML attribute
<body onpagehide="functionName()">

// JavaScript event listener
window.addEventListener('pagehide', function(event) {
    // Code to execute
});

Example: Basic Usage

Here's how to implement the onpagehide event using an HTML attribute:

<!DOCTYPE html>
<html>
   <body onpagehide="handlePageHide()">
      <p>Navigate away from this page to see the alert!</p>
      <a href="https://www.example.com">Click here to leave</a>
      <script>
         function handlePageHide() {
            alert("Thank you for visiting!");
         }
      </script>
   </body>
</html>

Using addEventListener Method

The modern approach uses addEventListener for better control and event handling:

<!DOCTYPE html>
<html>
   <body>
      <p>This page tracks when you leave using addEventListener</p>
      <script>
         window.addEventListener('pagehide', function(event) {
            console.log('Page is being hidden');
            
            // Check if page is being cached
            if (event.persisted) {
               console.log('Page will be cached');
            } else {
               console.log('Page will not be cached');
            }
         });
      </script>
   </body>
</html>

Event Properties

The pagehide event provides useful properties:

Property Type Description
persisted Boolean True if page goes into cache, false otherwise
type String Always "pagehide"

Common Use Cases

The onpagehide event is commonly used for:

  • Saving user data before leaving
  • Cleaning up timers and intervals
  • Logging user session information
  • Showing farewell messages

Browser Compatibility

The onpagehide event is supported in all modern browsers and is part of the HTML5 specification. It works reliably across Chrome, Firefox, Safari, and Edge.

Conclusion

The onpagehide event provides a reliable way to execute code when users leave your page. Use it for cleanup tasks, data saving, or user engagement tracking.

Updated on: 2026-03-15T23:18:59+05:30

504 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements