Browser Web APIs in JavaScript Complete Guide
A complete guide to browser Web APIs in JavaScript. Covers the DOM API, Fetch API, Web Storage, Geolocation, Intersection Observer, Resize Observer, Clipboard API, Notifications API, URL and URLSearchParams, and how Web APIs bridge JavaScript with browser capabilities.
Web APIs are browser-provided interfaces that JavaScript uses to interact with the outside world: the DOM, the network, storage, geolocation, clipboard, notifications, and more. They are not part of the JavaScript language itself but are available in the browser environment through the global window object.
What Are Web APIs?
| Category | APIs | Purpose |
|---|---|---|
| DOM | document.querySelector, element.classList | Read and modify the page |
| Network | fetch, XMLHttpRequest, WebSocket | HTTP requests, real-time data |
| Storage | localStorage, sessionStorage, IndexedDB | Persist data client-side |
| Observers | IntersectionObserver, ResizeObserver, MutationObserver | React to DOM changes |
| Clipboard | navigator.clipboard | Read/write clipboard |
| Geolocation | navigator.geolocation | Get user's physical location |
| Notifications | Notification | System-level notifications |
| URL | URL, URLSearchParams | Parse and build URLs |
DOM API Essentials
Querying Elements
// Single element
const header = document.querySelector("h1");
const button = document.querySelector("#submit-btn");
const card = document.querySelector(".card:first-child");
// Multiple elements (returns NodeList)
const items = document.querySelectorAll(".list-item");
items.forEach(item => item.classList.add("active"));Creating and Inserting Elements
const article = document.createElement("article");
article.className = "post";
article.innerHTML = `
<h2>${title}</h2>
<p>${excerpt}</p>
`;
// Append to container
document.querySelector(".feed").appendChild(article);
// Insert before a specific element
const feed = document.querySelector(".feed");
feed.insertBefore(article, feed.firstChild);Modifying Classes and Attributes
const el = document.querySelector(".card");
// Classes
el.classList.add("highlight");
el.classList.remove("hidden");
el.classList.toggle("expanded");
el.classList.contains("active"); // true or false
// Attributes
el.setAttribute("data-id", "42");
el.getAttribute("data-id"); // "42"
el.removeAttribute("data-id");
// Dataset (data-* attributes)
el.dataset.id = "42"; // sets data-id="42"
console.log(el.dataset.id); // "42"Fetch API
The Fetch API performs HTTP requests and returns Promises:
// GET request
const response = await fetch("/api/users");
const users = await response.json();
// POST request
const newUser = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Alice", email: "alice@example.com" }),
});See how to use the JS fetch API complete tutorial for the full Fetch guide.
Web Storage API
localStorage (Persists Across Sessions)
// Store
localStorage.setItem("theme", "dark");
localStorage.setItem("user", JSON.stringify({ name: "Alice" }));
// Retrieve
const theme = localStorage.getItem("theme"); // "dark"
const user = JSON.parse(localStorage.getItem("user")); // { name: "Alice" }
// Remove
localStorage.removeItem("theme");
// Clear all
localStorage.clear();sessionStorage (Current Tab Only)
// Same API as localStorage, but data is cleared when the tab closes
sessionStorage.setItem("formDraft", JSON.stringify(formData));
const draft = JSON.parse(sessionStorage.getItem("formDraft"));| Feature | localStorage | sessionStorage |
|---|---|---|
| Persistence | Until manually cleared | Until tab closes |
| Scope | Same origin, all tabs | Same origin, single tab |
| Size limit | ~5-10 MB | ~5-10 MB |
| Use case | User preferences, tokens | Form drafts, wizard state |
Intersection Observer
Detects when elements enter or exit the viewport, useful for lazy loading and infinite scroll:
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add("visible");
// Lazy load image
const img = entry.target.querySelector("img[data-src]");
if (img) {
img.src = img.dataset.src;
img.removeAttribute("data-src");
}
observer.unobserve(entry.target); // Stop observing once loaded
}
});
},
{ threshold: 0.1 } // Trigger when 10% visible
);
document.querySelectorAll(".lazy-section").forEach(el => observer.observe(el));Resize Observer
Reacts to element size changes (not just window resize):
const observer = new ResizeObserver(entries => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
console.log(`Element resized: ${width}x${height}`);
// Responsive component logic
entry.target.classList.toggle("compact", width < 400);
}
});
observer.observe(document.querySelector(".dashboard-panel"));Clipboard API
// Write to clipboard
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log("Copied!");
} catch (err) {
console.error("Copy failed:", err);
}
}
// Read from clipboard
async function pasteText() {
const text = await navigator.clipboard.readText();
return text;
}The Clipboard API requires a secure context (HTTPS) and user gesture (click event).
Geolocation API
function getLocation() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error("Geolocation not supported"));
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
resolve({
lat: position.coords.latitude,
lng: position.coords.longitude,
accuracy: position.coords.accuracy,
});
},
(error) => reject(error),
{ enableHighAccuracy: true, timeout: 10000 }
);
});
}
const location = await getLocation();
console.log(`Lat: ${location.lat}, Lng: ${location.lng}`);URL and URLSearchParams
// Parse a URL
const url = new URL("https://example.com/search?q=javascript&page=2#results");
console.log(url.hostname); // "example.com"
console.log(url.pathname); // "/search"
console.log(url.hash); // "#results"
// Work with query parameters
const params = url.searchParams;
console.log(params.get("q")); // "javascript"
console.log(params.get("page")); // "2"
// Build query strings
const newParams = new URLSearchParams({ q: "react", sort: "date", page: 1 });
console.log(newParams.toString()); // "q=react&sort=date&page=1"Notifications API
async function notify(title, body) {
if (Notification.permission === "default") {
await Notification.requestPermission();
}
if (Notification.permission === "granted") {
new Notification(title, {
body,
icon: "/icons/notification.png",
});
}
}
notify("New Message", "You have a new message from Alice");Rune AI
Key Insights
- Web APIs are browser-provided, not language features: They extend JavaScript with access to the DOM, network, storage, and device capabilities
- Feature detection is essential: Check
'API' in windowbefore using any Web API to avoid runtime errors in unsupported environments - Observers replace polling: IntersectionObserver, ResizeObserver, and MutationObserver are more efficient than setInterval-based checks
- Secure context required for sensitive APIs: Clipboard, Geolocation, and Notifications require HTTPS and often explicit user permission
- localStorage is synchronous and small: Use it for simple key-value preferences; use IndexedDB for larger structured data
Frequently Asked Questions
Are Web APIs available in Node.js?
What is the difference between Web APIs and the JavaScript language?
How do I check if a Web API is available?
Can Web APIs run on the main thread only?
What is the storage limit for localStorage?
Conclusion
Web APIs are the bridge between JavaScript and browser capabilities. The DOM API modifies the page, Fetch handles networking, Web Storage persists data, Observers react to changes efficiently, and specialized APIs handle clipboard, geolocation, and notifications. Always feature-detect before using an API and handle permission requirements gracefully. For the Fetch API in depth, see how to use the JS fetch API complete tutorial. For the event loop that coordinates these async APIs, see the JS event loop architecture complete guide.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.