JavaScript

How to Handle popstate Events in JavaScript

Ever since AJAX’s arrival, a lot of alterations have occurred on the web. With AJAX, the content of one page can be dynamically replaced with another one. All of this is not done by AJAX alone but it collaborates with other technologies like CSSOM properties, HTML DOM methods, and the History API.

The History API contains functionalities that are pushState() and replaceState() which work together with the popstate event. They are highly efficient and many are using it to support navigations in their applications.

This article discusses handling popstate events.

How to Handle popstate Events?

A popstate event is fired when a user tries to navigate through the session history set by the developer and the active history changes. When someone visits the page, the present history entry to the previous page gets changed. History entry is utilized when history.pushstate() adds a history entry to the history stack.

Syntax

window.onpopstate = function() {

  // handling the event

}

Event Type

A PopStateEvent takes all the properties from an Event.

Event Properties

PopStateEvent.state returns a duplicate of the information given to replaceState() or pushState().

Other than windows, the onpopstate property is also accessible on the following elements.

  • SVGSVGELEMENT
  • HTMLFrameSetElement
  • HTMLBodyElement

History API

Before coming to the popstate event, it is important to understand the history API and the replaceState() and pushState(). The stated functions make changes in the present session’s history in one way or another. A duplicate of the history entry’s state object is contained inside a popstate event.

Both of them integrate data into the history stack that builds a dynamic page or changes the state of the content. This happens on the same document. Calling pushState() or replaceState() will not fire a popState event. It can only be dispatched through the browser action like clicking on the forward or back event or in JavaScript, using history.forward() or history.back().

When is the popstate Event Fired?

The popState event is fired:

  • When a user navigates through the previous history session or there is any history traversal.
  • The new entry document is similar to the current entry. This can never happen with the page reload.

Examples

A popstate event fires on only one target i.e. windows. The popstate property can be handled in two ways:

  • Using the addEventListener() method and giving it an argument of popstate
  • Using the onpopstate handler property

Using the addEventListener() method

A page running will create logs as indicated in the example below. The following code shows the usage of the popstate event along with the history object to handle state changes and browser navigation:

window.addEventListener("popstate", (event) => {

      console.log(
        `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");
    history.back();
    history.back();

In the above code:

  • An addEventListener takes the argument “popstate” and the event gets triggered when the active history alters. This changes when a user tries to navigate through the browsing history.
  • On the dispatch of the event, the callback function logs the current location and the state associated with it.
  • history.pushState() adds a new state to the browsing history with the title and URL parameters.
  • history.replace() state changes the current history.
  • history.back() allows going one step back in history which triggers the popstate event and the last location and state are consoled.

Output:

The following output shows how a popstate event can be handled using addEventListener():

Using the onpopstate handler property

The above example will look like this if it uses the onpopstate handler property. The modifications in the code will be as follows:

window.onpopstate = (event) => {

  console.log(

    `location: ${document.location}, state: ${JSON.stringify(event.state)}`,

  );

};

Output:

The following output shows how a popstate event can be handled using the window.onstate property:

It is to be observed that the original history entry has no linkage with any state object. A popstate is dispatched when entry after the second call to the function history.back() is activated.

Conclusion

The window.onpopstate event is dispatched by the browser itself when the states set have been modified by the developer leading to a change in the active history. The popstate function is dispatched when the URL in the address is updated. This is beneficial in dynamically updating the present page content with the URL. History and popstate events play a critical role in powering complicated navigations in the present day’s application.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.