HTML Β· Chapter 42 of 45

HTML APIs (Geolocation and Storage)

Modern browsers expose HTML5 APIs that JavaScript can use to interact with device capabilities and persist data, without needing plugins. Two common ones are the Geolocation API and the Web Storage API.

The Geolocation API asks user permission to access their approximate location. The Web Storage API (localStorage and sessionStorage) lets you save key-value data directly in the browser, persisting across page reloads.

Syntax
localStorage.setItem(key, value); localStorage.getItem(key);

Geolocation API

navigator.geolocation.getCurrentPosition() requests the user's location, requiring explicit permission and typically HTTPS to work in modern browsers.

Web Storage API

localStorage persists data even after closing the browser. sessionStorage persists only for the current tab session. Both store simple string key-value pairs.

Example 1 (javascript)
navigator.geolocation.getCurrentPosition(pos => {
  console.log(pos.coords.latitude, pos.coords.longitude);
});
Output
(logs the user's latitude and longitude after permission is granted)

The callback receives a position object with coordinate data.

Example 2 (javascript)
localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme"));
Output
dark

localStorage persists this value even after the browser is closed and reopened.

Key points

  • The Geolocation API requests the user's approximate location.
  • Geolocation requires user permission and usually HTTPS.
  • localStorage persists data indefinitely across sessions.
  • sessionStorage clears when the browser tab is closed.
πŸ’‘ Note: Never store sensitive data like passwords in localStorage β€” it's accessible to any script on the page.

πŸ“ Quick Quiz

1. What does the Geolocation API require from the user?

2. Which storage persists across browser restarts?

3. Is it safe to store passwords in localStorage?