CodeBlanks Logo Icon CodeBlanks

Summary - History API

JavaScript course · Advanced · Lesson 83/100

Build a two-page SPA routing app with pushState and popstate.

Summary - History API

In this group you learned the basics of the History API: the history object gives access to the session history; pushState adds a new entry and changes the URL; replaceState updates the current entry; popstate fires on back or forward navigation.

history.pushState({path}, '', '/about');
window.addEventListener('popstate', (e) => {
  render(e.state.path);
});

Combine these to build a simple SPA router that works without page reloads.

Exercise Write a router function

Write a function named router(path). Inside it, call history.pushState with the state { path }, an empty string and path. Then call render(path) to update the view.

Show example solution
function router(path) {
  history.pushState({ path }, '', path);
  render(path);
}

Putting it together

The flow of an SPA router is: a link is clicked, the reload is stopped with preventDefault, the URL is updated with pushState, and the view is swapped with render. On back or forward, a popstate event fires and the right view is drawn from event.state.

function router(path) {
  history.pushState({ path }, '', path);
  render(path);
}
window.addEventListener('popstate', (e) => {
  if (e.state) router(e.state.path);
});

This structure is the core of modern client-side routing.

Exercise Restore the view on popstate

Add a 'popstate' listener to window. Use an arrow function with an event parameter. If event.state.path exists, call render(event.state.path); otherwise call render('/').

Show example solution
window.addEventListener('popstate', (event) => {
  if (event.state && event.state.path) {
    render(event.state.path);
  } else {
    render('/');
  }
});

Test yourself

  1. Which combination correctly handles back and forward in a SPA?

    • Using pushState alone is enough
    • Using replaceState alone is enough
    • Change views with pushState and catch back or forward with popstate
    • Do all routing inside window.onload
    Show answer

    Change views with pushState and catch back or forward with popstate — Correct! Route with pushState, catch back or forward with popstate.

  2. Match the History API summary

    pushState
    adds a new entry
    replaceState
    changes the current entry
    popstate
    back or forward event
    router
    handles routing

All lessons in Advanced