Execute a script when a user navigates away from a page in HTML?

When a user navigates away from a page, you can execute JavaScript code using the onpagehide event attribute. This event triggers when the user leaves the page by clicking a link, closing the browser tab, submitting a form, refreshing the page, or navigating to another URL.

The onpagehide event is part of the HTML5 Page Visibility API and provides a reliable way to detect when users are leaving your page, making it useful for cleanup tasks, saving user data, or logging analytics.

Syntax

Following are the different ways to use the onpagehide event −

HTML attribute syntax:

<body onpagehide="myFunction()">

JavaScript property syntax:

window.onpagehide = function() { /* script */ };

Event listener syntax:

window.addEventListener("pagehide", function() { /* script */ });

Using onpagehide with HTML Attribute

The onpagehide attribute can be added directly to the <body> element to execute a script when the user navigates away from the page.

Example

<!DOCTYPE html>
<html>
<head>
   <title>onpagehide HTML Attribute</title>
</head>
<body onpagehide="showAlert()" style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Page Hide Event Example</h2>
   <p>Try navigating away from this page (refresh, close tab, or click a link) to see the alert.</p>
   <a href="https://www.google.com">Navigate to Google</a>
   
   <script>
      function showAlert() {
         alert("You are leaving this page!");
      }
   </script>
</body>
</html>

When you attempt to navigate away from this page, an alert message will appear before the page unloads.

Using onpagehide with JavaScript Property

You can assign a function to the window.onpagehide property to handle the page hide event programmatically.

Example

<!DOCTYPE html>
<html>
<head>
   <title>onpagehide JavaScript Property</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Page Hide with JavaScript Property</h2>
   <p>This page will log a message when you navigate away.</p>
   <p>Open browser console (F12) and then try refreshing or navigating away.</p>
   <button onclick="location.reload()">Refresh Page</button>
   
   <script>
      window.onpagehide = function(event) {
         console.log("Page is being hidden. Persistent: " + event.persisted);
         // Save user data or perform cleanup
         localStorage.setItem("lastVisit", new Date().toString());
      };
   </script>
</body>
</html>

This example saves the current timestamp to localStorage whenever the user leaves the page. The event object provides a persisted property that indicates whether the page is being cached.

Using addEventListener for onpagehide

The modern approach is to use addEventListener() method, which allows multiple event listeners and better control over event handling.

Example

<!DOCTYPE html>
<html>
<head>
   <title>onpagehide with addEventListener</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Advanced Page Hide Detection</h2>
   <p>Form data will be automatically saved when you navigate away.</p>
   
   <form>
      <label for="username">Username:</label>
      <input type="text" id="username" placeholder="Enter your name"><br><br>
      
      <label for="email">Email:</label>
      <input type="email" id="email" placeholder="Enter your email"><br><br>
      
      <textarea id="comments" placeholder="Comments" style="width: 300px; height: 100px;"></textarea>
   </form>
   
   <p><a href="https://www.tutorialspoint.com">Go to TutorialsPoint</a></p>
   
   <script>
      window.addEventListener("pagehide", function(event) {
         // Save form data
         const formData = {
            username: document.getElementById("username").value,
            email: document.getElementById("email").value,
            comments: document.getElementById("comments").value,
            timestamp: new Date().getTime()
         };
         
         if (formData.username || formData.email || formData.comments) {
            localStorage.setItem("savedFormData", JSON.stringify(formData));
            console.log("Form data saved automatically");
         }
      });
      
      // Restore form data on page load
      window.addEventListener("load", function() {
         const savedData = localStorage.getItem("savedFormData");
         if (savedData) {
            const data = JSON.parse(savedData);
            document.getElementById("username").value = data.username || "";
            document.getElementById("email").value = data.email || "";
            document.getElementById("comments").value = data.comments || "";
         }
      });
   </script>
</body>
</html>

This example demonstrates automatic form data saving. Enter some text in the form fields, then navigate away and return to see the data restored.

onpagehide Event Flow User Action (navigate away) onpagehide Event Triggered JavaScript Executes ? Close tab ? Click link ? Refresh page ? Submit form ? Save data ? Cleanup ? Analytics

onpagehide vs onbeforeunload

While both events detect page navigation, they serve different purposes and have different behaviors:

onpagehide onbeforeunload
Fires after the page is hidden/unloaded Fires before the page is unloaded
Cannot prevent page navigation Can show confirmation dialog to prevent navigation
Works reliably across browsers Browser restrictions on showing dialogs
Best for cleanup and data saving Best for warning users about unsaved changes
Provides event.persisted property No persistence information

Common Use Cases

The onpagehide event is commonly used for −

  • Auto-saving form data − Prevent data loss when users accidentally navigate away

  • Analytics tracking − Record session duration and user behavior

  • Resource cleanup − Clear timers, close connections, or stop animations

  • State management − Save application state to localStorage or sessionStorage

Browser Compatibility

The onpagehide event is well-supported across modern browsers including Chrome, Firefox, Safari, and Edge. It is part of the HTML5 specification and provides more reliable page navigation detection compared to older methods.

Conclusion

The onpagehide event provides a reliable way to execute scripts when users navigate away from your page. Use it for cleanup tasks, auto-saving data, and tracking user behavior. The addEventListener approach offers the most flexibility and is recommended for modern web applications.

Updated on: 2026-03-16T21:38:53+05:30

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements