Skip to content

Browser APIs Interview Questions for Frontend Development

25 Browser APIs questions with answers for frontend development roles — 8 easy, 12 medium, 5 hard.

About Browser APIs

Browsers offer powerful built-in APIs that reduce the need for libraries. This topic covers Web Workers, service workers and caching strategies, observers, IndexedDB, the History and URL APIs, Web Components, postMessage, cross-tab communication and permissions, with practical tasks for offline support, clipboard and filter syncing.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Why use requestAnimationFrame instead of setTimeout for animations?

Save to ▾
Show answer
requestAnimationFrame runs your callback right before the browser paints the next frame, usually 60 or 120 times per second matching the display. It pauses in background tabs, saving battery, and avoids the drift and dropped frames that setTimeout causes because timers are not synced with rendering. The callback receives a high-precision timestamp, so animations can be calculated from elapsed time rather than fixed steps.
02

What is a Progressive Web App?

Save to ▾
Show answer
A Progressive Web App is a website that behaves like an installable app. It needs HTTPS, a web app manifest with name, icons and theme colour, and usually a service worker for offline support and caching. Users can add it to their home screen and it opens in a standalone window. PWAs are popular in India for lightweight apps that work on low-end phones and patchy mobile networks.
03

How do browser permission APIs like Geolocation and Notifications work?

Save to ▾
Show answer
Powerful features require user consent, a secure HTTPS context and usually a user gesture. Calling navigator.geolocation.getCurrentPosition or Notification.requestPermission shows a browser prompt; if the user denies it, you cannot ask again easily. navigator.permissions.query lets you check the current state first. Good UX explains why you need the permission before triggering the prompt, for example asking for location only when the user taps 'Find nearest centre'.
04

What are the URL and URLSearchParams APIs used for?

Save to ▾
Show answer
The URL constructor parses a URL into parts like hostname, pathname and searchParams, and builds valid URLs without manual string concatenation. URLSearchParams reads and writes query strings, handling encoding automatically, for example params.get('page') or params.set('sort', 'price'). They prevent bugs with special characters such as spaces and ampersands in search terms, and are the clean way to sync filters with the address bar.
05

Keep product filters in sync with the URL query string.

Save to ▾
Show answer
Read params on load and update them without reload: const params = new URLSearchParams(location.search); const category = params.get('category') ?? 'all'; applyFilters({ category }); function updateFilter(key, value) { const p = new URLSearchParams(location.search); value ? p.set(key, value) : p.delete(key); history.pushState(null, '', '?' + p.toString()); applyFilters(Object.fromEntries(p)); } window.addEventListener('popstate', () => applyFilters(Object.fromEntries(new URLSearchParams(location.search)))); Users can now share and bookmark filtered views.
06

Implement a copy-to-clipboard button with user feedback.

Save to ▾
Show answer
The async Clipboard API works in secure contexts after a user action: copyBtn.addEventListener('click', async () => { try { await navigator.clipboard.writeText(couponCode.textContent); copyBtn.textContent = 'Copied!'; } catch { copyBtn.textContent = 'Press Ctrl+C to copy'; } setTimeout(() => (copyBtn.textContent = 'Copy code'), 2000); }); An aria-live region can announce 'Copied' to screen reader users, since a changing button label may not always be read out.
07

A new browser API you used does not work in older Safari versions. How do you handle it?

Save to ▾
Show answer
I would use feature detection, such as if ('share' in navigator), rather than browser sniffing, and provide a fallback like a copy-link button. Checking Can I Use and the project's browser support list before building avoids surprises. Where reasonable, a small polyfill can fill gaps. This progressive enhancement approach ensures the core feature works everywhere while newer browsers get a better experience.
08

Tell me about a time you learned a new browser API to deliver a feature.

Save to ▾
Show answer
Situation: during my internship, the team wanted product images to load only when visible. Task: I was asked to implement it without adding a library. Action: I studied IntersectionObserver on MDN, built a small prototype, measured the page in Lighthouse and then applied it to the listing page with a fallback. Result: initial page weight dropped by about 60 percent, and the pattern was reused on other pages.
09

What is the difference between a Web Worker and a Service Worker?

Save to ▾
Show answer
A Web Worker runs JavaScript on a background thread for a single page, used for heavy computations like parsing files or image processing without freezing the UI. A Service Worker sits between the page and the network for an entire origin, intercepting requests to enable offline support, caching and push notifications. It has a lifecycle of install, activate and fetch, and it works only over HTTPS.
10

Compare IntersectionObserver, ResizeObserver and MutationObserver.

Save to ▾
Show answer
IntersectionObserver reports when an element enters or leaves the viewport or a container, used for lazy loading, infinite scroll and analytics impressions. ResizeObserver reports changes to an element's size, useful for charts that must redraw when their container changes. MutationObserver reports DOM changes like added nodes or changed attributes. All three are asynchronous and far more efficient than polling or scroll and resize listeners.
11

When should you use IndexedDB instead of localStorage?

Save to ▾
Show answer
localStorage is synchronous, stores only strings and is limited to about 5 MB, so large reads block the main thread. IndexedDB is asynchronous, stores structured data including blobs, supports indexes and transactions, and can hold hundreds of megabytes depending on disk space. Use it for offline data, drafts, cached API results or files in PWAs. Wrapper libraries like idb make its event-based API easier with promises.
12

How does the History API enable client-side routing?

Save to ▾
Show answer
history.pushState(state, '', '/courses/react') changes the URL and adds a history entry without reloading the page, and replaceState updates the current entry. When users press back or forward, the popstate event fires and the app renders the matching view. The server must return the app's HTML for all routes, otherwise refreshing a deep link gives a 404. Routers in SPA frameworks are built on this API.
13

What is the same-origin policy and how does postMessage work around it?

Save to ▾
Show answer
An origin is the combination of scheme, host and port. The same-origin policy stops scripts from reading data or DOM of another origin, such as an embedded iframe from a payment provider. window.postMessage lets two windows or iframes exchange messages safely across origins. The receiver must check event.origin against an allow-list, and the sender should specify the exact target origin instead of '*'.
14

How can you communicate between multiple tabs of the same site?

Save to ▾
Show answer
BroadcastChannel lets same-origin tabs, windows and workers publish and subscribe to messages on a named channel, which suits syncing logout, theme or cart updates. The storage event fires in other tabs when localStorage changes, which is a simple fallback. SharedWorker can hold shared state for all tabs. Each option works only within the same origin, so cross-domain sync needs a server or postMessage.
15

Move a heavy calculation into a Web Worker.

Save to ▾
Show answer
The worker runs on its own thread and talks through messages: // worker.js self.onmessage = (e) => { const total = e.data.reduce((sum, row) => sum + row.amount, 0); self.postMessage(total); }; // main.js const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }); worker.postMessage(bigArrayOfRows); worker.onmessage = (e) => showTotal(e.data); The UI stays responsive. Data is copied between threads, so for huge binary data use transferable objects like ArrayBuffer.
16

Detect offline status and retry queued requests when the connection returns.

Save to ▾
Show answer
Listen for online and offline events and keep a small queue: const queue = []; async function send(req) { if (!navigator.onLine) { queue.push(req); showBanner('You are offline'); return; } await fetch(req.url, req.options); } window.addEventListener('online', async () => { hideBanner(); while (queue.length) await send(queue.shift()); }); window.addEventListener('offline', () => showBanner('You are offline')); navigator.onLine can report true on captive networks, so treat failed fetches as offline too. Persist the queue in IndexedDB for reliability.
17

Create a simple custom element with Shadow DOM.

Save to ▾
Show answer
Extend HTMLElement and register a tag name containing a hyphen: class RatingStars extends HTMLElement { connectedCallback() { const value = Number(this.getAttribute('value') || 0); const root = this.attachShadow({ mode: 'open' }); root.innerHTML = `<style>span { color: var(--star-color, orange); }</style> <span role='img' aria-label='${value} out of 5'>${'*'.repeat(value)}</span>`; } } customElements.define('rating-stars', RatingStars); // usage: <rating-stars value='4'></rating-stars> The custom property lets the page theme it despite Shadow DOM isolation.
18

When a user logs out in one tab, other open tabs stay logged in. How do you fix it?

Save to ▾
Show answer
I would broadcast a logout message using BroadcastChannel, or the storage event as a fallback, so every tab clears its in-memory state and redirects to the login page. The server must also invalidate the session or refresh token, so stale tabs fail their next API call with a 401, which the app handles by logging out. Both client sync and server invalidation are needed.
19

In a single-page app, the back button takes users out of the site instead of to the previous filter. Why?

Save to ▾
Show answer
The app changes the view without adding history entries, so the browser has nothing to go back to within the site. Each meaningful navigation, like changing a category or opening a product, should call pushState or the router's navigate function, while minor changes such as typing in search can use replaceState. The app must also listen to popstate and restore the view and scroll position from the URL.
20

How do you handle unclear requirements from a product manager?

Save to ▾
Show answer
Situation: a product manager asked for 'offline support' in our web app without details. Task: I needed clarity before estimating. Action: I listed specific questions, which screens, read-only or editing, how long offline, and shared a quick prototype showing two options with effort estimates. Result: we agreed on read-only offline access for the order history, which shipped in one sprint instead of an open-ended project.
21

Explain common service worker caching strategies.

Save to ▾
Show answer
Cache-first serves from cache and falls back to network, ideal for versioned static assets. Network-first tries the network and falls back to cache, suited to HTML and API data that should be fresh. Stale-while-revalidate returns the cached copy immediately while fetching an update in the background, good for avatars or non-critical data. Libraries like Workbox implement these strategies and handle cache expiry and versioning.
22

What are Web Components and Shadow DOM?

Save to ▾
Show answer
Web Components are native, framework-independent reusable elements built from Custom Elements, Shadow DOM and HTML templates. Shadow DOM attaches an encapsulated DOM tree to an element, so its styles do not leak out and page styles do not leak in, except through CSS custom properties and ::part. They are used for design systems shared across React, Angular and plain HTML apps. Server rendering and form participation need extra work.
23

Register a service worker that caches static assets with a cache-first strategy.

Save to ▾
Show answer
Register from the page, then handle install and fetch in sw.js: // main.js if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js'); // sw.js const CACHE = 'static-v3'; self.addEventListener('install', e => { e.waitUntil(caches.open(CACHE).then(c => c.addAll(['/', '/app.css', '/app.js']))); }); self.addEventListener('fetch', e => { e.respondWith(caches.match(e.request).then(hit => hit || fetch(e.request))); }); Changing the cache name on each release lets the activate step delete old caches.
24

After a deployment, some users keep seeing the old version of your PWA. Why?

Save to ▾
Show answer
The old service worker is still controlling the page and serving cached files; a new worker waits until all tabs using the old one are closed. I would version the cache, delete old caches in the activate event, and show an 'Update available' prompt that calls skipWaiting and reloads. The sw.js file itself must be served with no-cache headers so browsers check for updates promptly.
25

Your page embeds a payment iframe from another domain and needs its result. How do you do it safely?

Save to ▾
Show answer
The iframe should send the result with parent.postMessage(data, 'https://yourshop.com'), and the page listens for message events, checking event.origin against the exact payment domain and validating the data shape before acting. The frontend message should only update UI; the final payment status must be confirmed from your server through the gateway's webhook or verification API, since messages can be spoofed.

Frequently asked questions

How important is Browser APIs in Frontend Development interviews?

Browsers offer powerful built-in APIs that reduce the need for libraries. This topic covers Web Workers, service workers and caching strategies, observers, IndexedDB, the History and URL APIs, Web Components, postMessage, cross-tab communication and permissions, with practical tasks for offline support, clipboard and filter syncing.

How should I use the Browser APIs sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.