HTML onpopstate Event Attribute

Description

The event attribute onpopstate is an event handler for the popstate event on the window.

A popstate event is dispatched to the window each 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.

Syntax

<element onpopstate="script">

Values

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

Example

<!DOCTYPE html> 
<html> 
  
<body> 
<p>Reload page to trigger event</p>
    <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://www.cssportal.com/html-event-attributes/onpopstate.php?page=1, 
        // state: {"page":1}" 
        history.back(); 
  
        // alerts "location: about:blank, state: null" 
        history.back(); 
    </script> 
</body> 
  
</html> 

Browser Support

Desktop
Explorer Edge Chrome Firefox Opera Safari
??????
Tablets / Mobile
Android Chrome Firefox Opera Safari Samsung
??????