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).
Web Storage APIs
Client Key-Value Store
localStorage: Permanent origin storage (~5-10MB).sessionStorage: Tab-scoped lifecycle store.setItem(),getItem(),removeItem().
Hardware & Sensor APIs
Device Integrations
navigator.geolocation: GPS / Wi-Fi coordinates.navigator.clipboard: Async clipboard read/write.Notification API: OS-level system alerts.
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:
// 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
}
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:
// 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:
🎯 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=Strictcookies. - Concurrency: Web Workers communicate via message passing (
postMessage) and do not have access to the window DOM directly.