Web Foundations

History API

SPA navigation, pushState, popstate, and browser history management.

Advertisement

History API

SPA navigation, pushState, popstate, and browser history management.

Overview

History API enables single-page application navigation.

Key Concepts

  • pushState — Add history entry
  • replaceState — Replace current entry
  • popstate — Back/forward navigation
  • Hash Routing — URL hash-based routing
  • State Management — Store data with history entries

Code Examples

<nav>
  <a href="/" data-link>Home</a>
  <a href="/about" data-link>About</a>
  <a href="/contact" data-link>Contact</a>
</nav>

<main id="app"></main>

<script>
const routes = {
  '/': '<h1>Home Page</h1><p>Welcome to our site</p>',
  '/about': '<h1>About Us</h1><p>Learn more about us</p>',
  '/contact': '<h1>Contact</h1><p>Get in touch</p>'
};

function navigate(url) {
  history.pushState({ url }, '', url);
  render(url);
}

function render(url) {
  const content = routes[url] || '<h1>404 Not Found</h1>';
  document.getElementById('app').innerHTML = content;
}

// Handle link clicks
document.querySelectorAll('[data-link]').forEach(link => {
  link.addEventListener('click', (e) => {
    e.preventDefault();
    navigate(link.getAttribute('href'));
  });
});

// Handle back/forward
window.addEventListener('popstate', (e) => {
  render(e.state?.url || window.location.pathname);
});

// Handle initial load
render(window.location.pathname);

// Hash-based routing
window.addEventListener('hashchange', () => {
  const hash = window.location.hash.slice(1) || '/';
  render(hash);
});

// State with history
function addToHistory(state) {
  history.pushState({ data: state }, '', `?id=${state.id}`);
}

window.addEventListener('popstate', (e) => {
  if (e.state?.data) {
    console.log('Restored state:', e.state.data);
  }
});
</script>

Practice

Build a simple router using the History API.

Advertisement