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.

JavaScriptintermediate
14 min read

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?

CategoryAPIsPurpose
DOMdocument.querySelector, element.classListRead and modify the page
Networkfetch, XMLHttpRequest, WebSocketHTTP requests, real-time data
StoragelocalStorage, sessionStorage, IndexedDBPersist data client-side
ObserversIntersectionObserver, ResizeObserver, MutationObserverReact to DOM changes
Clipboardnavigator.clipboardRead/write clipboard
Geolocationnavigator.geolocationGet user's physical location
NotificationsNotificationSystem-level notifications
URLURL, URLSearchParamsParse and build URLs

DOM API Essentials

Querying Elements

javascriptjavascript
// 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

javascriptjavascript
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

javascriptjavascript
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:

javascriptjavascript
// 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)

javascriptjavascript
// 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)

javascriptjavascript
// 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"));
FeaturelocalStoragesessionStorage
PersistenceUntil manually clearedUntil tab closes
ScopeSame origin, all tabsSame origin, single tab
Size limit~5-10 MB~5-10 MB
Use caseUser preferences, tokensForm drafts, wizard state

Intersection Observer

Detects when elements enter or exit the viewport, useful for lazy loading and infinite scroll:

javascriptjavascript
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):

javascriptjavascript
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

javascriptjavascript
// 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

javascriptjavascript
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

javascriptjavascript
// 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

javascriptjavascript
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

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 window before 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
RunePowered by Rune AI

Frequently Asked Questions

Are Web APIs available in Node.js?

Most are not. Web APIs are browser-specific. Node.js provides its own APIs (`fs`, `http`, `crypto`). Some APIs like `fetch`, `URL`, `TextEncoder`, and `structuredClone` are now available in Node.js as well.

What is the difference between Web APIs and the JavaScript language?

The JavaScript language (ECMAScript) defines syntax, types, and built-in objects like Array and Promise. Web APIs are host environment features provided by the browser. You can use JavaScript without any Web APIs (e.g., in Node.js).

How do I check if a Web API is available?

Feature detection: `if ('IntersectionObserver' in window)` or `if (navigator.clipboard)`. Never rely on user-agent sniffing.

Can Web APIs run on the main thread only?

Most do. However, `fetch`, `IndexedDB`, and `postMessage` are available in Web Workers. DOM APIs are main-thread only.

What is the storage limit for localStorage?

Typically 5-10 MB per origin, depending on the browser. For larger data, use IndexedDB, which supports hundreds of megabytes.

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.