HTML5 APIs Interview Questions
This lesson explains HTML5 APIs Interview Questions with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.
HTML5 APIs Interview Questions and Answers
These HTML5 APIs interview questions help frontend developers prepare for
junior, senior, and architect-level interviews. The questions cover
browser APIs, storage, media, files, workers, performance, offline apps,
accessibility, security, and real-world web application use cases.
Junior HTML5 APIs Interview Questions
- 1. What are HTML5 APIs?
HTML5 APIs are browser features that allow JavaScript to access native
browser capabilities such as storage, geolocation, media, canvas,
drag-and-drop, files, workers, notifications, and network requests.
- 2. What is the Fetch API?
The Fetch API is a modern Promise-based API used to make HTTP requests.
It is commonly used to call REST APIs, load JSON data, upload files, and
download resources.
- 3. How do you make a basic GET request using Fetch?
fetch("/api/users")
.then((response) => response.json())
.then((users) => {
console.log(users);
});
- 4. What is Local Storage?
Local Storage stores small key-value data in the browser with no
automatic expiration. It is useful for themes, preferences, and simple
client-side settings.
- 5. What is the difference between Local Storage and Session Storage?
Local Storage persists until manually cleared. Session Storage is
limited to the current browser tab and is cleared when the tab closes.
- 6. How do you store and read data from Local Storage?
localStorage.setItem("theme", "dark");
const theme =
localStorage.getItem("theme");
console.log(theme);
- 7. What is the Geolocation API?
The Geolocation API requests the user's location with permission and
returns coordinates such as latitude, longitude, and accuracy.
- 8. How do you check whether Geolocation is supported?
if ("geolocation" in navigator) {
console.log("Geolocation supported.");
} else {
console.log("Geolocation not supported.");
}
- 9. What is the Canvas API?
The Canvas API provides a pixel-based drawing surface for creating
graphics, charts, games, animations, image editors, and visual effects
using JavaScript.
- 10. What is the File API?
The File API allows web applications to access files selected by users
through file inputs or drag-and-drop without immediately uploading them
to a server.
- 11. What is FileReader?
FileReader reads the contents of user-selected files as text, Base64
data URLs, ArrayBuffer binary data, or legacy binary strings.
- 12. What is the Drag and Drop API?
The Drag and Drop API lets users drag elements, files, text, links, or
images into drop targets within a page or from the desktop into the
browser.
- 13. Why is
event.preventDefault() needed in dragover?
It tells the browser that the element is a valid drop target. Without
calling preventDefault(), the drop event may
not fire.
- 14. What is the Fullscreen API?
The Fullscreen API displays an HTML element, such as a video, canvas,
game, presentation, or dashboard, using the entire screen.
- 15. What is feature detection?
Feature detection checks whether a browser supports an API before using
it. This is more reliable than checking browser names.
- 16. Give one feature detection example.
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js");
}
Senior HTML5 APIs Interview Questions
- 1. Why does Fetch not reject on HTTP 404 or 500 responses?
Fetch only rejects for network failures, CORS failures, or request
cancellation. HTTP error responses still resolve successfully, so
developers must check response.ok or
response.status.
- 2. How do you handle Fetch errors correctly?
async function loadUsers() {
try {
const response =
await fetch("/api/users");
if (!response.ok) {
throw new Error("HTTP Error: " + response.status);
}
const users =
await response.json();
return users;
} catch (error) {
console.error(error.message);
return [];
}
}
- 3. When should you use IndexedDB instead of Local Storage?
Use IndexedDB for large structured data, offline-first apps, files,
blobs, search indexes, cached API responses, and transactional data. Use
Local Storage only for small string-based preferences.
- 4. What are IndexedDB object stores and transactions?
Object stores are like tables that hold records. Transactions control
safe read and write operations using modes such as
readonly and readwrite.
- 5. Why should object stores be created inside
onupgradeneeded?
IndexedDB schema changes are allowed only during version upgrades.
onupgradeneeded is the correct place to create object
stores and indexes.
- 6. What is the difference between FileReader and Object URLs?
FileReader reads file contents into memory. Object URLs provide a
temporary URL for previewing files or blobs more efficiently, especially
for large images or videos.
- 7. Why should you call
URL.revokeObjectURL()?
Object URLs hold browser resources. Calling
URL.revokeObjectURL() releases memory when the preview or
download URL is no longer needed.
- 8. How do Web Workers improve performance?
Web Workers run JavaScript in a background thread, allowing heavy
calculations, parsing, image processing, or data transformation without
blocking the main UI thread.
- 9. What can Web Workers not access?
Web Workers cannot directly access the DOM, document, or
page elements. They communicate with the main thread using
postMessage().
- 10. How do you pass data to a Worker?
const worker =
new Worker("/worker.js");
worker.postMessage(
{
type: "PROCESS",
items: [1, 2, 3]
}
);
worker.addEventListener("message", (event) => {
console.log(event.data);
});
- 11. What is the Intersection Observer API used for?
It detects when elements enter or leave the viewport or scroll
container. Common uses include lazy loading, infinite scrolling,
analytics impressions, scroll animations, and active navigation.
- 12. Why is Intersection Observer better than scroll events for visibility tracking?
It is browser-optimized and avoids repeated manual layout calculations.
Scroll events can be expensive unless carefully throttled or debounced.
- 13. What are
root, rootMargin, and threshold?
root is the viewport or scroll container,
rootMargin expands or shrinks the observation area, and
threshold defines how much of the target must be visible.
- 14. How do you stop camera or microphone access from
getUserMedia()?
stream.getTracks()
.forEach((track) => {
track.stop();
});
- 15. What security rules apply to powerful HTML5 APIs?
Many APIs require HTTPS, user gestures, and explicit permissions. This
includes Clipboard, Geolocation, Notifications, Camera, Microphone,
Service Workers, and File System Access.
- 16. Why should you not store sensitive data in Local Storage?
Local Storage is accessible to JavaScript. If an XSS vulnerability
exists, attackers can read tokens or sensitive values stored there.
- 17. When should cookies be preferred over Local Storage?
Cookies are better for server-managed sessions, especially when using
HttpOnly, Secure, and
SameSite attributes to reduce XSS and CSRF risks.
- 18. What is the Broadcast Channel API?
Broadcast Channel enables same-origin communication between browser
tabs, windows, iframes, and workers. It is useful for logout sync, theme
sync, cart updates, and notification state.
- 19. How do you create a Blob download?
const blob =
new Blob(
["Hello"],
{ type: "text/plain" }
);
const url =
URL.createObjectURL(blob);
const link =
document.createElement("a");
link.href = url;
link.download = "message.txt";
link.click();
URL.revokeObjectURL(url);
Architect HTML5 APIs Interview Questions
- 1. How would you design an offline-first web application using HTML5 APIs?
Use Service Workers for request interception and caching, Cache API for
static assets and API responses, IndexedDB for structured offline data,
Background Sync for retrying failed writes, and a conflict-resolution
strategy for syncing local changes with the server.
- 2. How would you choose between Local Storage, IndexedDB, Cache API, and cookies?
Use cookies for secure server sessions, Local Storage for small
non-sensitive preferences, IndexedDB for large structured app data, and
Cache API for HTTP request and response caching through Service Workers.
- 3. How would you handle authentication storage securely in a browser app?
Prefer secure HttpOnly, Secure,
SameSite cookies for session tokens. Avoid storing tokens
in Local Storage. Add CSRF protection, short token lifetimes, refresh
rotation, CSP, and strong XSS prevention.
- 4. How would you build a high-performance file upload system?
Combine File API, Drag and Drop, file validation, preview via Object
URLs, chunked uploads, retry logic, upload progress, cancellation,
server-side validation, malware scanning, and accessible upload states.
- 5. How would you process a 500 MB CSV file in the browser?
Avoid loading the full file into memory. Use streaming or chunked file
reading, process chunks in a Web Worker, update progress in the UI,
store intermediate results in IndexedDB if needed, and provide
cancellation.
- 6. How would you design a media recording web application?
Use getUserMedia() to capture camera or microphone,
MediaRecorder to record streams, Blob to store chunks, Object URLs for
preview, IndexedDB for temporary drafts, and Fetch or chunked uploads
for server persistence.
- 7. How would you design cross-tab logout?
Use secure cookies for authentication and Broadcast Channel or storage
events to notify other tabs. When one tab logs out, clear client state,
invalidate the server session, and broadcast a logout message.
- 8. How would you improve performance for image-heavy pages?
Use responsive images, native lazy loading, Intersection Observer,
modern formats, image compression, CDN caching, explicit dimensions to
reduce layout shift, and priority hints for critical images.
- 9. How would you design an accessible drag-and-drop kanban board?
Support mouse, touch, and keyboard reordering. Provide buttons such as
Move Up, Move Down, Move to Next Column, use ARIA live announcements,
visible focus states, clear instructions, and preserve logical DOM
order.
- 10. How would you build a client-side router using the History API?
Use pushState() for navigation, replaceState()
for redirects or filters, listen for popstate, render
content based on location.pathname, and configure the
server to return the app shell for deep links.
- 11. How do Service Workers, Cache API, and IndexedDB work together?
Service Workers intercept network requests, Cache API stores HTTP
responses and static assets, while IndexedDB stores structured
application data such as drafts, user records, offline changes, and sync
queues.
- 12. How would you handle privacy-sensitive APIs at architecture level?
Request permissions only after clear user intent, explain why access is
needed, collect minimum data, avoid unnecessary storage, encrypt
sensitive data, provide revocation controls, log access responsibly, and
comply with privacy requirements.
- 13. How would you design graceful degradation for unsupported APIs?
Use feature detection, progressive enhancement, fallback UI, server-side
alternatives, manual input options, and avoid making experimental APIs
required for core workflows.
- 14. How would you avoid main-thread blocking in a data-heavy web app?
Move CPU-heavy tasks to Web Workers, use incremental rendering, virtual
lists, requestIdleCallback where appropriate, streaming parsers,
pagination, memoization, and avoid repeated layout reads and writes.
- 15. How would you design reliable browser API error handling?
Centralize feature detection, permission checks, timeout handling,
retries, fallback behavior, user-friendly error messages, telemetry, and
cleanup logic for media streams, object URLs, workers, and observers.
- 16. What browser APIs would you use for a modern PWA?
Use Service Workers, Cache API, IndexedDB, Web App Manifest, Push API,
Notifications API, Background Sync, Fetch API, and feature detection for
offline-ready and installable app behavior.
- 17. How would you optimize scroll-based UI features?
Use Intersection Observer for visibility, Resize Observer for size
changes, Mutation Observer for DOM updates, CSS sticky positioning
where possible, and throttled scroll listeners only when continuous
scroll position is required.
- 18. How would you build a browser-based image editor?
Use File API for image selection, Object URLs for preview, Canvas or
OffscreenCanvas for rendering, Web Workers for filters, Blob for export,
Download API patterns for saving, and accessibility alternatives for
important controls.
- 19. What trade-offs should architects consider when using HTML5 APIs?
Consider browser support, security, privacy, performance, offline
behavior, data size, memory usage, accessibility, permissions, mobile
compatibility, fallback requirements, testing complexity, and long-term
maintainability.
HTML5 APIs Coding Interview Examples
- 1. Write a reusable Fetch helper with error handling.
async function apiRequest(url, options = {}) {
const response =
await fetch(url, options);
if (!response.ok) {
throw new Error("HTTP Error: " + response.status);
}
return response.json();
}
- 2. Create a lazy loading image observer.
const observer =
new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const image =
entry.target;
image.src =
image.dataset.src;
observer.unobserve(image);
}
});
});
document
.querySelectorAll("img[data-src]")
.forEach((image) => {
observer.observe(image);
});
- 3. Preview an uploaded image using Object URL.
function previewImage(file, image) {
const url =
URL.createObjectURL(file);
image.src = url;
image.onload = () => {
URL.revokeObjectURL(url);
};
}
- 4. Save a JSON file using Blob.
function downloadJson(data) {
const blob =
new Blob(
[JSON.stringify(data, null, 2)],
{ type: "application/json" }
);
const url =
URL.createObjectURL(blob);
const link =
document.createElement("a");
link.href = url;
link.download = "data.json";
link.click();
URL.revokeObjectURL(url);
}
- 5. Detect API support before using Geolocation.
function getLocation() {
if (!("geolocation" in navigator)) {
return Promise.reject(
new Error("Geolocation not supported")
);
}
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
resolve,
reject
);
});
}
Interview Tip
For senior and architect interviews, do not only define APIs. Explain
trade-offs: browser support, HTTPS requirements, permissions, privacy,
memory cleanup, accessibility, fallbacks, performance, offline behavior,
and real-world architecture decisions.