HTML5 APIs (Geolocation, Storage)

Difficulty: Intermediate

Question

What are the key HTML5 APIs? Explain localStorage vs sessionStorage.

Answer

HTML5 introduced powerful browser APIs:

1. Web Storage: localStorage (persists) vs sessionStorage (per tab) 2. Geolocation: get user's location with permission 3. Web Workers: background threads for heavy computation 4. History API: manipulate browser history (SPA routing) 5. Canvas/WebGL: 2D/3D graphics 6. Drag and Drop: native drag/drop support

localStorage vs sessionStorage: - localStorage: persists until manually cleared, shared across tabs - sessionStorage: cleared when tab closes, per-tab isolation - Both: ~5MB limit, synchronous, strings only

Code examples

localStorage vs sessionStorage

// localStorage: persists across sessions
localStorage.setItem('theme', 'dark');
localStorage.getItem('theme'); // 'dark'
localStorage.removeItem('theme');
localStorage.clear(); // remove all

// Store objects (must serialize)
const user = { name: 'John', age: 25 };
localStorage.setItem('user', JSON.stringify(user));
const stored = JSON.parse(
  localStorage.getItem('user')
);

// sessionStorage: same API, per-tab lifetime
sessionStorage.setItem('formDraft', '{...}');
// Gone when tab closes

// Listen for storage changes (cross-tab)
window.addEventListener('storage', (e) => {
  console.log(e.key, e.oldValue, e.newValue);
  // Only fires in OTHER tabs
});

localStorage persists forever (until cleared). sessionStorage is isolated per tab. Both store strings only - use JSON.stringify/parse for objects.

Geolocation API

// Check support
if ('geolocation' in navigator) {
  // One-time position
  navigator.geolocation.getCurrentPosition(
    (position) => {
      const { latitude, longitude } = position.coords;
      console.log(`Lat: ${latitude}, Lng: ${longitude}`);
      console.log(`Accuracy: ${position.coords.accuracy}m`);
    },
    (error) => {
      switch (error.code) {
        case error.PERMISSION_DENIED:
          console.log('User denied geolocation');
          break;
        case error.POSITION_UNAVAILABLE:
          console.log('Location unavailable');
          break;
        case error.TIMEOUT:
          console.log('Request timed out');
          break;
      }
    },
    { enableHighAccuracy: true, timeout: 10000 }
  );

  // Watch position (continuous)
  const watchId = navigator.geolocation.watchPosition(
    (pos) => console.log(pos.coords)
  );
  navigator.geolocation.clearWatch(watchId);
}

Geolocation requires user permission (HTTPS only in production). Always handle errors gracefully - the user may deny access.

History API for SPA Routing

// Push new state (no page reload)
history.pushState(
  { page: 'about' },  // state object
  '',                  // title (ignored by most browsers)
  '/about'             // new URL
);

// Replace current state
history.replaceState(
  { page: 'home' }, '', '/'
);

// Listen for back/forward navigation
window.addEventListener('popstate', (e) => {
  console.log('Navigation:', e.state);
  // Render the appropriate page
  renderPage(e.state?.page || 'home');
});

// Go back/forward programmatically
history.back();
history.forward();
history.go(-2); // go back 2 pages

React Router, Vue Router, and other SPA routers are built on top of the History API. pushState changes the URL without a page reload.

Key points

Concepts covered

localStorage, sessionStorage, Geolocation, Web Workers, History API