HTML5 Web APIs & Client Storage

Master LocalStorage, SessionStorage, IndexedDB, Geolocation, Canvas 2D, Drag and Drop, and Web Workers.

1. Modern Client Storage & Web Platform APIs

HTML5 revolutionized web development by giving browsers native capabilities once exclusive to desktop applications: rich client-side persistence, hardware sensor access, background multi-threading, and 2D/3D hardware-accelerated rendering.

💡 Real-World Analogy: Sticky Notes vs Home Locker vs Bank Vault

Think of client storage mechanisms like everyday personal organization:
• Cookies (~4KB): Sticky Notes on Every Letter — Every time you send an envelope to the server, the postal carrier brings every sticky note along with it (high network overhead).
• SessionStorage (~5MB): Conference Room Whiteboard — You write meeting notes while the tab is open; the second you close the room door (tab closed), the board is wiped clean.
• LocalStorage (~5-10MB): Your Home Steel Locker — Stored permanently on your device across browser restarts until you explicitly clean it out.
• IndexedDB (Gigabytes+): An Underground Bank Vault — Structured, transactional, indexed NoSQL database for large offline datasets and Progressive Web Apps (PWAs).

01

Web Storage APIs

Client Key-Value Store

  • localStorage: Permanent origin storage (~5-10MB).
  • sessionStorage: Tab-scoped lifecycle store.
  • setItem(), getItem(), removeItem().
02

Hardware & Sensor APIs

Device Integrations

  • navigator.geolocation: GPS / Wi-Fi coordinates.
  • navigator.clipboard: Async clipboard read/write.
  • Notification API: OS-level system alerts.
03

Graphics & Threads

High Performance

  • <canvas>: 2D / WebGL pixel graphics surface.
  • Web Workers: Background thread execution.
  • Drag & Drop API: Native draggable UI events.

2. Client Storage Comparison Matrix

Choosing the correct storage mechanism is a common architectural decision tested in technical placement interviews:

Feature Cookies LocalStorage SessionStorage IndexedDB
Capacity Limit ~4 KB per cookie ~5 MB - 10 MB ~5 MB > 250 MB (Gigabytes)
Lifetime / Expiration Configurable via Expires/Max-Age Permanent (until user/JS clears) Destroyed on tab close Permanent (until cleared)
Sent with HTTP Requests? Yes (Every request automatically) No (Strictly client-side) No (Strictly client-side) No (Strictly client-side)
Execution Model Synchronous (via document.cookie) Synchronous (blocks UI thread) Synchronous (blocks UI thread) Asynchronous (Non-blocking)
Primary Use Case Session IDs (with HttpOnly, Secure) UI themes, cart IDs, cached preferences Multi-step form wizard states Offline PWAs, media files, full search indexes

3. Interactive LocalStorage State & Theme Controller

The code below demonstrates storing structured state with JSON serialization and handling live user preferences:

HTML + JS Source Code storage-demo.js
// Save object to localStorage (JSON Serialization)
function saveUserData(user) {
  localStorage.setItem('candidate', JSON.stringify(user));
}

// Retrieve & parse from localStorage
function loadUserData() {
  const raw = localStorage.getItem('candidate');
  return raw ? JSON.parse(raw) : { name: 'Anshuman', score: 85 };
}

// Clear specific key or wipe entire origin
function clearData() {
  localStorage.removeItem('candidate');
  // localStorage.clear(); // Wipes all keys
}
Rendered Browser Output ● Live Preview
⚡ Live Storage State Inspector Storage Active
Candidate Score State:
85 / 100 points
localStorage.getItem('score') ➔ 85

4. Geolocation & HTML5 Canvas 2D Rendering

The Geolocation API retrieves hardware GPS or network-triangulated coordinates with explicit user permission, while the <canvas> element offers a programmable bitmap drawing surface:

Geolocation API & 2D Canvas Drawing
// 1. Geolocation API with robust error handling
if ('geolocation' in navigator) {
  navigator.geolocation.getCurrentPosition(
    (pos) => {
      console.log(`Latitude: ${pos.coords.latitude}, Longitude: ${pos.coords.longitude}`);
    },
    (err) => {
      console.warn('Location error code:', err.code, err.message);
    },
    { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }
  );
}

// 2. HTML5 Canvas 2D Context Drawing
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Draw glowing gradient rectangle
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, '#6366F1');
gradient.addColorStop(1, '#3B82F6');
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 160, 80);

5. Test Your Knowledge: HTML5 APIs & Storage Quiz

Evaluate your understanding of client persistence, XSS vulnerabilities, and Web APIs:

🎯 HTML5 APIs & Storage Interview Deck
Question 1 of 5
⭐ High Frequency • Web Security XSS & LocalStorage
Why should sensitive authentication tokens (like secret refresh tokens) NOT be stored in localStorage?
A) LocalStorage automatically encrypts all values with AES-512, making them unreadable.
B) LocalStorage only allows numeric values.
C) LocalStorage is accessible to any JavaScript running on the domain, making tokens vulnerable to Cross-Site Scripting (XSS) theft.
D) LocalStorage clears its database whenever the user scrolls down.
⭐ Lifecycle Difference Storage Lifespans
What is the primary difference in lifecycle between localStorage and sessionStorage?
A) LocalStorage is deleted every 24 hours; SessionStorage persists permanently.
B) LocalStorage persists indefinitely until manually cleared; SessionStorage is destroyed when the browser tab closes.
C) SessionStorage is automatically sent to the backend server with every HTTP request.
D) LocalStorage requires an active internet connection to read keys.
⭐ Performance & Threading Synchronous Storage
Are localStorage.setItem() and getItem() synchronous or asynchronous operations?
A) Synchronous — they run on the main thread and can block UI rendering during heavy operations.
B) Asynchronous — they return a Promise that must be resolved with await.
C) Multi-threaded via background Web Workers by default.
D) They run strictly in Node.js server runtimes.
⭐ Serialization Standard JSON in Storage
What is the correct way to store a JavaScript object { id: 1, role: 'Admin' } inside localStorage?
A) localStorage.setItem('user', [object Object]);
B) localStorage.writeBinary('user', object);
C) localStorage.setItem('user', object.toXML());
D) localStorage.setItem('user', JSON.stringify(object)); and JSON.parse() on retrieval.
⭐ Multi-Threading Web Workers
What is the primary architectural purpose of HTML5 Web Workers?
A) To automatically convert CSS rules into WebAssembly.
B) To bypass the browser's Same-Origin Policy for cross-domain cookie sharing.
C) To execute heavy computational tasks on a separate background thread without freezing the main UI thread.
D) To compress images before saving to disk.

🎯 Placement Interview Master Takeaways

  • Storage Tradeoffs: Cookies (~4KB, sent with every HTTP request), LocalStorage (~5-10MB persistent client storage), SessionStorage (~5MB per-tab lifecycle), IndexedDB (GBs asynchronous NoSQL).
  • Security: Never place secret JWTs in LocalStorage due to XSS vulnerability. Store auth tokens in HttpOnly, Secure, SameSite=Strict cookies.
  • Concurrency: Web Workers communicate via message passing (postMessage) and do not have access to the window DOM directly.