HTML onpopstate attribute

HTML onpopstate attribute: The HTML onpopstate attribute is triggered when the history of the window changes. And the onpopstate event is dispatched to the window every time the active history entry changes between two history entries for the same document. If the activated history entry was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event’s state property contains a copy of the history entry’s state object.

HTML onpopstate attribute

This attribute supports all the event attributes and can be applied to <body> element.

Property

state: This property/method returns an object containing a copy of the history entries

Event Types

popstate: This event occurs when the window’s history changes

Browser Support

This attribute was supported by different browsers.

  • Chrome
  • Firefox
  • InternetExplorer
  • Safari
  • Opera

Example:

<!DOCTYPE html> 
<html> 

<body> 
  <script> 
    window.onpopstate = function(event) { 
    alert("location: " + document.location + 
    ", state: " + JSON.stringify(event.state)); 
    }; 
    history.pushState({ 
      page: 1 
    }, "title 1", "?page=1"); 
    history.pushState({ 
      page: 2 
    }, "title 2", "?page=2"); 
    history.replaceState({ 
      page: 3 
    }, "title 3", "?page=3"); 

    // alerts "location: 
    // https://ide.freshersnow.com/tryit.php?page=1, 
    // state: {"page":1}" 
    history.back(); 

    // alerts "location: about:blank, state: null" 
    history.back(); 
  </script> 
</body> 

</html>

Output:

html onpopstate attribute