Web APIs
📖 Concept
Web APIs are browser-provided APIs that extend JavaScript's capabilities beyond the language itself. They let you interact with device hardware, observe DOM changes, and create rich user experiences.
Key Web APIs covered:
- Geolocation API — Get user's geographic location
- Notifications API — Show system notifications
- Intersection Observer — Detect when elements enter/exit the viewport
🏠 Real-world analogy: Web APIs are like the utilities in a building (electricity, water, internet). The building (browser) provides them, and your apartment (JavaScript) can use them through standard interfaces (API).
💻 Code Example
1// Geolocation API2if ("geolocation" in navigator) {3 navigator.geolocation.getCurrentPosition(4 (position) => {5 console.log("Lat:", position.coords.latitude);6 console.log("Lng:", position.coords.longitude);7 console.log("Accuracy:", position.coords.accuracy, "meters");8 },9 (error) => {10 switch(error.code) {11 case error.PERMISSION_DENIED: console.log("User denied"); break;12 case error.POSITION_UNAVAILABLE: console.log("Unavailable"); break;13 case error.TIMEOUT: console.log("Timed out"); break;14 }15 },16 { enableHighAccuracy: true, timeout: 10000 }17 );18}1920// Notifications API21async function showNotification() {22 const permission = await Notification.requestPermission();23 if (permission === "granted") {24 new Notification("Hello!", {25 body: "This is a notification from your app",26 icon: "/icon.png"27 });28 }29}3031// Intersection Observer — lazy loading / infinite scrolling32const observer = new IntersectionObserver(33 (entries) => {34 entries.forEach(entry => {35 if (entry.isIntersecting) {36 const img = entry.target;37 img.src = img.dataset.src; // Load actual image38 observer.unobserve(img); // Stop watching39 }40 });41 },42 { threshold: 0.1, rootMargin: "100px" }43);44// Observe all lazy images45document.querySelectorAll("img[data-src]").forEach(img => {46 observer.observe(img);47});4849// Clipboard API50async function copyToClipboard(text) {51 await navigator.clipboard.writeText(text);52 console.log("Copied!");53}5455// Broadcast Channel — cross-tab communication56const channel = new BroadcastChannel("app");57channel.postMessage({ type: "logout" });58channel.onmessage = (e) => {59 if (e.data.type === "logout") window.location.href = "/login";60};
🏋️ Practice Exercise
Mini Exercise:
- Build a "Get My Location" button that shows coordinates on a map
- Implement lazy-loading images using Intersection Observer
- Create a notification-based reminder app
- Build infinite scroll using Intersection Observer
⚠️ Common Mistakes
Not checking for API support before using it — always use
if ('geolocation' in navigator)Forgetting Notifications require HTTPS and user permission — handle denied permissions gracefully
Not disconnecting/unobserving Intersection Observers — can cause memory leaks
Blocking the UI while waiting for geolocation — always use async patterns
Not handling all error cases for Geolocation (permission denied, unavailable, timeout)
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Web APIs. Login to unlock this feature.