Skip to content

14. A Field Guide to Browser APIs

“Before you npm install it, check whether the browser already ships it.”

Your grandfather’s toolbox sits in the store room. You’ve been borrowing tools from neighbours for years — a spirit level here, a stud finder there — because you assumed the old box held only a hammer and some rusty screwdrivers. One day you actually open it. There’s a laser level. A set of precision drivers. A multimeter. Some of it is brand new; someone has been quietly restocking it.

That’s the web platform. Many developers learned it in an era when you needed a library for everything — jQuery for selecting elements, a library for modals, one for animations, one for detecting visibility. Meanwhile, the browser vendors kept restocking the box. Today, many of those libraries reimplement, in hundreds of kilobytes of main-thread JavaScript, things the browser does natively, faster, and accessibly.

This chapter is a field guide: what’s in the box, what each tool is for, the one-line mental model, and a short example. It’s not exhaustive. It’s the set a senior frontend engineer should be able to reach for without a search.

Before the tour, the method. Three sources:

  • MDN — the reference for every API, with a browser compatibility table at the bottom of each page.
  • caniuse.com — support tables across browsers and versions, with global usage percentages.
  • Baseline — a cross-vendor label (shown on MDN and caniuse) that summarizes support: Newly available means the feature works in the current versions of all major browsers (Chrome, Edge, Firefox, Safari); Widely available means it’s been newly available for at least 30 months, long enough that older browser versions have mostly aged out.

The mindset that goes with it is progressive enhancement: build the core experience with widely available features, and layer newer features on top where supported, with feature detection (if ('IntersectionObserver' in window), CSS.supports(…), @supports). A user on an old WebView gets a working page; a user on a current browser gets a nicer one.

Progressive enhancement layersThree stacked layers. Bottom: HTML that works everywhere — links, forms, content. Middle: CSS and JavaScript widely available features. Top: newer enhancements such as view transitions, speculation rules and scroll-driven animations, applied only where supported via feature detection.Core: semantic HTML, real links and forms — works everywhereWidely available CSS + JS: layout, fetch, observers, dialogEnhancements if supported: view transitions, prerender…
Figure 14.1. Progressive enhancement: a baseline that works everywhere, with enhancements layered on where the browser supports them — never the other way round.

Old code polled: check scroll position on every scroll event, check sizes on every resize, re-query the DOM to see if something changed. Each check potentially forced layout on the main thread (Chapter 10). Observers invert this: you register interest, and the browser tells you, asynchronously and efficiently, when something happens.

IntersectionObserver — “tell me when this element enters or leaves the viewport (or another container).” For lazy-loading, infinite scroll triggers, pausing off-screen animations and videos, analytics impressions.

const io = new IntersectionObserver((entries) => {
for (const e of entries) e.target.classList.toggle('visible', e.isIntersecting);
}, { rootMargin: '200px' });
document.querySelectorAll('.card').forEach((c) => io.observe(c));

This is precisely the fix for the author’s gallery in Chapter 16: pause glass surfaces and canvases that aren’t on screen.

ResizeObserver — “tell me when this element’s size changes.” The right way to build container-aware components without forced layout (though for pure styling, CSS container queries are better still).

MutationObserver — “tell me when the DOM under this node changes.” For reacting to third-party DOM changes, editors, or integration glue. Callbacks are microtasks; heavy work inside them can pile up.

PerformanceObserver — “tell me when performance entries are recorded”: largest-contentful-paint, layout-shift, event (interaction timings), long-animation-frame, resource, navigation. It’s the foundation of real-user monitoring (Chapters 16–17).

new PerformanceObserver((list) => {
for (const e of list.getEntries()) console.log('LCP candidate', e.startTime, e.element);
}).observe({ type: 'largest-contentful-paint', buffered: true });

fetch is the modern HTTP client. Three things people don’t know about it:

  1. It doesn’t reject on HTTP errors. A 404 or 500 resolves normally; check response.ok.
  2. Bodies are streams. response.body is a ReadableStream; you can process data as it arrives — render a long list progressively, show download progress, parse newline-delimited JSON line by line, or consume an AI model’s token stream.
  3. It’s cancellable via AbortController:
const ctrl = new AbortController();
fetch('/api/search?q=chai', { signal: ctrl.signal }).catch((e) => {
if (e.name !== 'AbortError') throw e;
});
ctrl.abort(); // the user typed another letter; cancel the stale request

Cancelling stale requests prevents a classic race: the response for “ch” arriving after the response for “chai” and overwriting the right results. AbortSignal.timeout(5000) gives you a timeout; AbortSignal.any([...]) combines signals. The same signal pattern works with addEventListener to remove many listeners at once — handy for component cleanup.

Compression Streams (CompressionStream('gzip')) and TextDecoderStream let you pipe data through transforms natively.

The JavaScript interface to the same animation engine CSS uses:

const anim = card.animate(
[{ transform: 'scale(0.96)', opacity: 0 }, { transform: 'none', opacity: 1 }],
{ duration: 220, easing: 'cubic-bezier(.2,.8,.2,1)', fill: 'both' }
);
await anim.finished;

Because it’s the native engine, transform/opacity animations created with WAAPI can run on the compositor (Chapter 10), unlike rAF-driven JS animations. And unlike CSS animations, you can control them: pause(), reverse(), playbackRate, currentTime (scrub with a slider), and promises for completion. Chapter 19 builds on it.

Covered mechanically in Chapter 10: document.startViewTransition(update) for same-document changes, and @view-transition { navigation: auto } for cross-document navigations. The field-guide summary: the browser snapshots before and after, and animates between them with pseudo-elements you can style. Give elements a matching view-transition-name on both sides and they morph (a thumbnail growing into a hero image). Wrap it in feature detection; without support, the update just happens instantly.

Two features that delete a surprising amount of JavaScript.

<dialog> — a native dialog element. dialog.showModal() opens it as a modal: it’s rendered in the top layer (above everything, no z-index wars), the rest of the page becomes inert (not clickable, not focusable, hidden from assistive tech), focus moves into the dialog, and Escape closes it. Style the backdrop with ::backdrop. This is most of what a hand-written modal library does, with the accessibility done right (Chapter 15).

The Popover API — add popover to any element and a popovertarget button opens it:

<button popovertarget="menu">Options</button>
<div id="menu" popover>…menu items…</div>

You get top-layer rendering, light dismiss (click outside or press Escape closes it), and correct focus handling — no JavaScript at all. Combined with CSS anchor positioning (positioning an element relative to another element, purely in CSS), menus, tooltips and pickers become declarative.

navigator.clipboard.writeText('…') and readText() (plus write/read for images and rich content). Asynchronous, permission-gated, available only in secure contexts and generally only in response to a user gesture. Replaces the old document.execCommand('copy') hack.

document.visibilityState and the visibilitychange event tell you when the page is hidden (tab switched, app backgrounded, screen locked). Pause animations, video, polling and expensive work when hidden. And critically: visibilitychange to hidden is the last reliable moment to send analytics, because on mobile, pages are often discarded from the background without any unload event. That’s why RUM libraries flush there (with navigator.sendBeacon or fetch with keepalive).

The Page Lifecycle model adds frozen (the browser suspends a background tab’s task queues to save battery; events freeze/resume) and discarded (the tab was unloaded to save memory; document.wasDiscarded tells you on reload). And as Chapter 9 said: use pagehide, not unload.

Page lifecycle statesStates: active, passive, hidden, frozen, discarded or terminated. Arrows: active to passive on blur, passive to hidden on visibilitychange, hidden to frozen, frozen to discarded. A note on hidden says flush analytics here.ActivePassiveHiddenFrozenDiscardedflush analytics here(visibilitychange → hidden)
Figure 14.2. The page lifecycle. On mobile, a hidden page may be frozen or discarded without further warning — so 'hidden' is your last reliable signal.

Talk between tabs, windows and workers of the same origin:

const ch = new BroadcastChannel('lumen');
ch.postMessage({ type: 'logout' });
ch.onmessage = (e) => { if (e.data.type === 'logout') location.reload(); };

Log out in one tab, and all tabs follow. Sync a “saved” state across tabs. Coordinate a single tab doing background sync.

navigator.share({ title, text, url }) opens the OS’s native share sheet — on Android, the familiar WhatsApp/Telegram/Instagram list. For an Indian audience where sharing happens in WhatsApp, this is a meaningful feature for a few bytes. Requires a user gesture; feature-detect and fall back to copy-link.

navigator.geolocation.getCurrentPosition(…) triggers a permission prompt. Powerful APIs (location, camera, microphone, notifications, clipboard read) are gated by permissions, granted per origin, requested only in secure contexts, and increasingly only in response to user gestures. The navigator.permissions.query({ name: 'geolocation' }) API tells you the current state without prompting.

The UX rule: ask in context. Prompting on page load (“this site wants your location”) gets denied and is hard to recover from (once denied, you can’t re-prompt; the user has to dig into settings). Ask when the user taps “Find essays near me,” and explain why first.

Notifications show OS-level notifications from a page or service worker (after permission). Push lets your server send a message to a user’s browser even when your site isn’t open: the browser vendor’s push service delivers it to your service worker, which shows a notification. It requires a service worker, a push subscription, and user permission. It’s powerful and easily abused; prompting for push permission on first visit is the fastest way to get your site’s prompts blocked by users and, increasingly, quieted by browsers.

Real-time: WebSockets vs. SSE vs. WebTransport

Section titled “Real-time: WebSockets vs. SSE vs. WebTransport”
  • WebSockets — a persistent, full-duplex connection over a single TCP connection (upgraded from HTTP). Both sides send messages anytime. Chat, collaboration, games. Costs: you manage reconnection, heartbeats, back-pressure; load balancers and proxies must support long-lived connections.
  • Server-Sent Events (SSE) — new EventSource('/stream'): a one-way stream of text events from server to client over plain HTTP, with automatic reconnection built in. For notifications, live feeds, progress updates, and AI token streams, SSE is often the simpler right answer. Works naturally over HTTP/2 (many streams on one connection).
  • WebTransport — a newer API over HTTP/3/QUIC: multiple independent streams and unreliable datagrams, without TCP’s head-of-line blocking. For games, media and low-latency data where some loss is acceptable. Support is newer; feature-detect.
Real-time transports comparedThree columns: SSE, one-way server to client over HTTP with auto reconnect; WebSockets, two-way messages over a TCP connection; WebTransport, multiple streams and unreliable datagrams over QUIC.SSEserver → client onlyplain HTTP, text eventsauto-reconnect built infeeds, progress, AI tokensWebSockettwo-way messagesone TCP connectionyou handle reconnectschat, collaborationWebTransportmany streams + datagramsHTTP/3 / QUICno TCP HOL blockinggames, media, low latency
Figure 14.3. Choosing a real-time transport. Start with the simplest that fits: SSE for server → client, WebSockets for two-way, WebTransport when you need QUIC's properties.

WebRTC gives browsers peer-to-peer audio, video and data channels: video calls in the browser without plugins. Under the hood: capturing media, encoding, NAT traversal (ICE, with STUN to discover your public address and TURN relays when direct connection fails), encryption, and adaptive bitrate. You’ll still need a signalling server to introduce peers, and TURN servers cost money. Most teams use a hosted service or SDK rather than raw WebRTC.

WebAssembly (Wasm) is a compact binary instruction format that browsers compile to fast machine code. You compile C, C++, Rust, Go and others to it. It runs in the same sandbox as JS, calls into JS (and through JS, the DOM). Good for: CPU-heavy, portable code — image and video codecs, physics engines, CAD, SQLite in the browser (with OPFS, Chapter 12), design tools. Not a replacement for JS in UI code: crossing the JS↔Wasm boundary has a cost, and the DOM is still JS’s job. And Wasm modules are bytes that must be downloaded and compiled — streaming compilation helps, but a 10 MB Wasm file is still 10 MB on Priya’s network.

You can check feature support with MDN, caniuse and Baseline; apply progressive enhancement; use the four observers instead of polling; stream, cancel and time out fetches; drive animations with WAAPI; replace modal and popover libraries with <dialog> and popover; use visibility as your last reliable signal; coordinate tabs; share natively; ask for permissions in context; choose between SSE, WebSockets and WebTransport; and place WebRTC and WebAssembly correctly.

1. What does “Baseline widely available” mean?

Supported in all major browsers for at least 30 months.

2. Why is IntersectionObserver better than a scroll listener that checks positions?

It’s asynchronous and computed by the browser without forcing layout on every scroll event.

3. Does fetch reject on a 500?

No; check response.ok.

4. What does showModal() give you for free?

Top-layer rendering, inert background, focus moved into the dialog, Escape to close, ::backdrop.

5. When should analytics be flushed on mobile?

On visibilitychange to hidden (with sendBeacon/keepalive), because pages may be discarded without unload.

Warm-up 1. Pick the API. Which API for: (a) pause a video when scrolled away; (b) a component that changes layout based on its own width; (c) a live score ticker; (d) sharing an essay to WhatsApp.

Solution

(a) IntersectionObserver; (b) container queries (or ResizeObserver); (c) SSE; (d) Web Share.

Warm-up 2. Race condition. A search box fires a fetch per keystroke; old results sometimes overwrite new ones. Fix it.

Solution

Abort the previous request with an AbortController on each new keystroke (and/or ignore responses for stale queries).

Warm-up 3. Permission timing. Why is a location prompt on page load a bad idea?

Solution

No context, likely denied, and once denied you can’t prompt again — the feature is lost for that user.

Lab 4. Native lightbox. Replace Lumen’s custom lightbox with <dialog> + showModal(). Check keyboard and screen-reader behaviour.

Expected outcome

Less JS; Escape closes; focus moves in and returns to the thumbnail; background is inert.

Lab 5. Share and copy. Add a share button to Lumen essays: Web Share where supported, copy-link via the Clipboard API otherwise.

Hint

Feature-detect navigator.share; trigger both from a click handler (user gesture required).

Lab 6. Tab sync. Use BroadcastChannel so saving an essay in one Lumen tab updates the “saved” icon in all open tabs.

Expected outcome

Instant cross-tab updates without polling storage.

Lab 7. Stream a list. Serve Lumen’s essay index as newline-delimited JSON and render items as they stream in via response.body.

Expected outcome

The first items appear before the full response has downloaded — visible under network throttling.

Staff 8. Library audit. List five dependencies in a real project that the platform now covers natively. Estimate KB saved and risks of migrating.

Model approach

Map each library to its native replacement with Baseline status; note behavioural differences, browser support gaps for your audience, and migration cost; prioritize by bytes × usage.