Execute a script when the window's history changes in HTML?

The onpopstate event in HTML triggers when the browser's history changes, such as when a user clicks the back or forward button. This event is essential for handling navigation in single-page applications and managing browser history programmatically.

Syntax

Following is the syntax for the onpopstate event −

<body onpopstate="functionName()">

In JavaScript, you can also add the event listener programmatically −

window.addEventListener('popstate', functionName);

How It Works

The onpopstate event fires when the active history entry changes. This happens when users navigate using browser buttons (back/forward) or when history.back(), history.forward(), or history.go() methods are called. The event does not fire when history.pushState() or history.replaceState() are used.

The event object contains a state property that holds the state data associated with the history entry, which was previously set using pushState() or replaceState().

Using Inline onpopstate

Example

Following example shows how to use the onpopstate event inline in the body tag −

<!DOCTYPE html>
<html>
<head>
   <title>Onpopstate Event Example</title>
</head>
<body onpopstate="onpopstateFunction()" style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Browser History Navigation Demo</h2>
   <p id="demo">Navigate using browser back/forward buttons to see the event in action.</p>
   <button onclick="addHistoryEntry()">Add History Entry</button>
   <p id="status"></p>

   <script>
      function onpopstateFunction() {
         document.getElementById("status").innerHTML = "History changed! Timestamp: " + new Date().toLocaleTimeString();
      }

      function addHistoryEntry() {
         history.pushState({page: "new"}, "New Page", "?page=new");
         document.getElementById("demo").innerHTML = "New history entry added. Use back button to trigger onpopstate.";
      }
   </script>
</body>
</html>

Click the button to add a history entry, then use the browser's back button to trigger the onpopstate event −

Browser History Navigation Demo
Navigate using browser back/forward buttons to see the event in action.
[Add History Entry]

(After clicking button and then back button)
History changed! Timestamp: 2:30:45 PM

Using addEventListener Method

Example

Following example demonstrates using the addEventListener method for better event handling −

<!DOCTYPE html>
<html>
<head>
   <title>Onpopstate with addEventListener</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>History State Management</h2>
   <div>
      <button onclick="goToPage1()">Go to Page 1</button>
      <button onclick="goToPage2()">Go to Page 2</button>
      <button onclick="goToPage3()">Go to Page 3</button>
   </div>
   <p id="currentPage">Current Page: Home</p>
   <p id="stateData"></p>

   <script>
      // Add event listener for popstate
      window.addEventListener('popstate', function(event) {
         if (event.state) {
            document.getElementById("currentPage").innerHTML = "Current Page: " + event.state.page;
            document.getElementById("stateData").innerHTML = "State Data: " + JSON.stringify(event.state);
         } else {
            document.getElementById("currentPage").innerHTML = "Current Page: Home";
            document.getElementById("stateData").innerHTML = "State Data: None";
         }
      });

      function goToPage1() {
         history.pushState({page: "Page 1", id: 1}, "Page 1", "?page=1");
         document.getElementById("currentPage").innerHTML = "Current Page: Page 1";
      }

      function goToPage2() {
         history.pushState({page: "Page 2", id: 2}, "Page 2", "?page=2");
         document.getElementById("currentPage").innerHTML = "Current Page: Page 2";
      }

      function goToPage3() {
         history.pushState({page: "Page 3", id: 3}, "Page 3", "?page=3");
         document.getElementById("currentPage").innerHTML = "Current Page: Page 3";
      }
   </script>
</body>
</html>

This example creates multiple history entries. Navigate using the buttons and then use browser back/forward buttons to see the onpopstate event retrieve the stored state data −

History State Management
[Go to Page 1] [Go to Page 2] [Go to Page 3]
Current Page: Page 2
State Data: {"page":"Page 2","id":2}

Practical Use Case

Example − Single Page Application Navigation

Following example shows a practical implementation for a single-page application −

<!DOCTYPE html>
<html>
<head>
   <title>SPA Navigation with onpopstate</title>
   <style>
      .page { display: none; padding: 20px; border: 1px solid #ccc; margin: 10px 0; }
      .active { display: block; }
      nav button { margin: 5px; padding: 8px 16px; }
   </style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h1>Single Page Application Demo</h1>
   <nav>
      <button onclick="navigateTo('home')">Home</button>
      <button onclick="navigateTo('about')">About</button>
      <button onclick="navigateTo('contact')">Contact</button>
   </nav>

   <div id="home" class="page active">
      <h2>Home Page</h2>
      <p>Welcome to the home page of our SPA demo.</p>
   </div>

   <div id="about" class="page">
      <h2>About Page</h2>
      <p>This is the about section of our single page application.</p>
   </div>

   <div id="contact" class="page">
      <h2>Contact Page</h2>
      <p>Get in touch with us through this contact page.</p>
   </div>

   <script>
      // Handle browser back/forward navigation
      window.addEventListener('popstate', function(event) {
         if (event.state && event.state.page) {
            showPage(event.state.page);
         } else {
            showPage('home');
         }
      });

      function navigateTo(page) {
         history.pushState({page: page}, page, '?page=' + page);
         showPage(page);
      }

      function showPage(page) {
         // Hide all pages
         var pages = document.querySelectorAll('.page');
         pages.forEach(function(p) {
            p.classList.remove('active');
         });
         
         // Show selected page
         document.getElementById(page).classList.add('active');
      }

      // Set initial state
      history.replaceState({page: 'home'}, 'home', '?page=home');
   </script>
</body>
</html>

This creates a functional single-page application where users can navigate between sections and use browser back/forward buttons seamlessly.

onpopstate Event Flow User clicks back/forward History entry changes onpopstate event fires Browser Navigation History API Event Handler

Key Points

  • The onpopstate event only fires when navigating between history entries, not when creating new ones with pushState() or replaceState().

  • The event object contains a state property with data previously stored in the history entry.

  • This event is crucial for single-page applications to maintain proper navigation behavior.

  • Always check if event.state exists before accessing its properties, as initial page loads may have null state.

Conclusion

The onpopstate event is essential for handling browser history changes in modern web applications. It enables proper back/forward button functionality in single-page applications by detecting when users navigate through their browser history. Use it with the History API to create seamless navigation experiences.

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

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements