Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

`Window` events: `popstate` and `hashchange`

Use `popstate` to read the state of an activated history entry and `hashchange` to detect a URL fragment change within the same document.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

window.addEventListener("popstate", handlePopState); // PopStateEvent: event.state
window.addEventListener("hashchange", handleHashChange); // HashChangeEvent: event.oldURL, event.newURL

// Alternative: assign one handler per property.
window.onpopstate = handlePopState;
window.onhashchange = handleHashChange;

The term Window.popstate/hashchange events refers to two distinct events defined by the web platform, not by ECMAScript. Listen on window with addEventListener(). The window.onpopstate and window.onhashchange properties are alternatives: assigning a new handler replaces the one previously assigned to that property.

popstate signals activation of a different session history entry, for example when going Back or Forward within the same document. PopStateEvent.state contains the restored value saved for the destination entry, or null if no state was saved. Same-document fragment navigation can also fire popstate. Do not rely on this event to initialize the view: a browser may withhold it until the user has interacted with the page.

hashchange signals a change to the URL fragment within the same document, for example after following a link to #details or setting location.hash to a new fragment. HashChangeEvent.oldURL and HashChangeEvent.newURL are full URLs, not just fragments. If the same operation fires both events, popstate comes first.

history.pushState() adds an entry, whereas history.replaceState() updates the current one. Neither call itself fires either event, even if it changes the fragment. Render the initial view yourself and update it directly after a successful history write in your code. If you listen for both events, avoid applying the same update twice.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>History events demo</title>
</head>
<body>
  <button id="run-history-demo" type="button">Run history demo</button>
  <script>
    (() => {
      const button = document.getElementById("run-history-demo");
      button.addEventListener("click", () => {
        button.remove();

        window.addEventListener("popstate", (event) => {
          console.log(`popstate: ${JSON.stringify(event.state)}`);
        }, { once: true });

        window.addEventListener("hashchange", (event) => {
          const from = new URL(event.oldURL).hash;
          const to = new URL(event.newURL).hash;
          console.log(`hashchange: ${from} -> ${to}`);
        }, { once: true });

        history.replaceState({ view: "overview" }, "", "#overview");
        history.pushState({ view: "details" }, "", "#details");
        console.log(`after writes: ${location.hash}`);
        history.back();
      }, { once: true });
    })();
  </script>
</body>
</html>

Result

after writes: #details
popstate: {"view":"overview"}
hashchange: #details -> #overview

Save the example as `index.html`, serve it over HTTP(S), and open it in a disposable browser tab: the demo modifies history entries. Open the DevTools console and click “Run history demo” on the page. The two history writes fire neither event; the asynchronous return logs the `overview` state and the fragment change.

Related lessons

  • JavaScript · Lesson 36 · Intermediate · Version: 3
  • JavaScript · Lesson 37 · Intermediate · Version: 3

Sources