JavaScript - History & Storage APIs

Overview

Estimated time: 10–15 minutes

The History and Storage APIs allow you to manage browser history and persist data on the client side.

Learning Objectives

  • Use the History API to manipulate browser navigation.
  • Store and retrieve data using localStorage and sessionStorage.

Prerequisites

History API

history.pushState({ page: 2 }, 'title 2', '?page=2');
window.onpopstate = function(event) {
  console.log(event.state);
};

Storage API

localStorage.setItem('key', 'value');
console.log(localStorage.getItem('key'));
sessionStorage.setItem('token', 'abc');

Common Pitfalls

  • Storage is limited and only stores strings.

Summary

History and Storage APIs are essential for modern web apps that need navigation and persistence.