HTML onpopstate Event Attribute


The HTML onpopstate event attribute is triggered when the history of the window changes. This can happen when the user clicks the back or forward buttons, or when the developer uses the history.pushState() or history.replaceState() methods to update the history stack.

The onpopstate event is a good way to keep track of the user's navigation history and update the page accordingly. For example, you could use it to highlight the current page in a navigation bar, or to load different content depending on the user's previous page.

To use the onpopstate event attribute, you would add it to the <body> element of your HTML document. The value of the attribute should be a JavaScript function that will be called when the event is triggered.

Here is an example of how to use the onpopstate event attribute:

<body onpopstate="myFunction()">
function myFunction() {
  // Update the page based on the user's navigation history

The onpopstate event object contains a number of properties that can be used to get information about the current history entry. These properties include:

  • state: An object containing any data that was passed to the history.pushState() or history.replaceState() methods.
  • type: The type of history navigation that occurred. This can be "push", "replace", or "pop".
  • hash: The hash fragment of the current URL.


<element onpopstate="script">


  • scriptThe name of the script to use when the event has been triggered.


<!DOCTYPE html> 

<p>Reload page to trigger event</p>
window.onpopstate = function(event) {
alert("EXAMPLE: location: " + document.location +
", state: " + JSON.stringify(event.state));
page: 1
}, "title 1", "?page=1");
page: 2
}, "title 2", "?page=2");
page: 3
}, "title 3", "?page=3");

// alerts "location:
// state: {"page":1}"

// alerts "location: about:blank, state: null"


Browser Support

The following table will show you the current browser support for the HTML onpopstate Event Attribute.

Edge Chrome Firefox Opera Safari
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview

Last updated by CSSPortal on: 14th October 2023