Workbench / Volume 2 Exercises: The Web Frontend
V2·12
The Web Platform
Exercises for Volume 2, chapter 12, with the volume's "Start Here: How the Web Works" chapter folded in: clients, servers and the three languages of the browser, URLs and origins, sites and schemeful sites, browsing contexts and documents, navigation and session history, resource loading and script order, the DOM, CSSOM and accessibility trees, the JavaScript runtime and event loop, storage, and the browser's security model (same-origin policy, CORS, cookies, CSP). 12 theory questions, 11 programming exercises, 3 cumulative projects with Volume 1, the concepts the chapter leaves out, and 6 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking as Volume 1. This page also covers the volume's opening chapter, 00 Start Here: How the Web Works: its ideas (client and server, what HTML, CSS and JavaScript each do, how a page loads, reading the first error) are the foundation of T1, T2 and P1, so there's no separate page for it.
The programming exercises run in a real browser: open DevTools (F12) and use the Console, Elements, Network and Application panels. For the two-origin exercises (P5–P7), run two local servers on different ports, for example python3 -m http.server 8001 and python3 -m http.server 8002 in the same folder. The outputs in the solutions come from Chromium 153 driven by Playwright in this book's sandbox; Firefox and Safari give the same results except where noted.
The cumulative projects combine this chapter with all of Volume 1 (chapters 01–11): the web platform is where Volume 1's networking, security, encoding and concurrency ideas meet the user.
Coverage map.
| Chapter component | Exercises |
|---|---|
| clients and servers; frontend and backend; HTML, CSS and JS roles (Start Here) | T1, P1 |
| what the browser does with a page; reading errors (Start Here) | T2, P1 |
| the web platform vs a native runtime | T3 |
| URLs: anatomy, encoding, relative resolution | T4, P2 |
| origins; sites and schemeful sites | T5, P3 |
| browsing contexts, documents, navigables, frames | T6, P7 |
| navigation and session history | T6, P10 |
| resource loading; parser-blocking, defer, async and module scripts | T7, P4 |
| the DOM; attributes vs properties | T8, P8 |
| the CSSOM; the accessibility tree | T8, P9 |
| the JavaScript runtime in the page: event loop, tasks, microtasks, rendering | T9, P11 |
| storage: cookies, localStorage, sessionStorage, IndexedDB, Cache API, quotas | T10, P6 |
| the security model: same-origin policy, CORS, cookies' flags, CSP, isolation | T11, T12, P5, P7, P10 |
Theory
T1. Client, server and the three languages
- When you open
https://tiffinbox.in/kitchens/42, which parts happen on your phone and which on TiffinBox's servers? Use the words client, server, frontend, backend, request and response. - What does each of HTML, CSS and JavaScript do? For a "menu" page with a list of dishes, a price filter and an "Add to cart" button, say which language is responsible for each part, and what the page still does if JavaScript fails to load.
- A colleague from a Java backend team says "the frontend is just a view layer". Give three reasons why browser code is a distributed-systems client in its own right (Volume 1, chapter 09's fallacies).
T2. What the browser does with a page
- Put these in order and say what each produces: DNS lookup, TCP+TLS, HTML parsing, CSS parsing, DOM, CSSOM, render tree / layout, paint, composite, JavaScript execution,
DOMContentLoaded,load. - The Start Here chapter's first error was a typo in a script. Explain the difference between an error that stops the page entirely, one that stops one script, and one that only shows in the Console. Where in DevTools do you look for each?
- Why can a page show content before all its images have loaded but not before its CSS has loaded?
T3. The platform versus a native runtime
Compare the web platform with a JVM application or a native mobile app on: distribution and updates, sandboxing, access to the file system and devices, the threading model, standards and versioning, and performance. When would TiffinBox choose a web app, a native app, or both?
T4. URLs
- Label every part of
https://asha:secret@api.tiffinbox.in:8443/v1/kitchens/42/menu?veg=1&max=200#reviews. Which parts are sent to the server, and which never leave the browser? - P2 parsed
https://bücher.example/a b?q=₹ 5#top: the host becamexn--bcher-kva.example, the path/a%20band the query?q=%E2%82%B9%205, whilesearchParams.get('q')returned₹ 5. Explain each transformation (Volume 1, chapter 06's UTF-8). - Resolve against
https://tiffinbox.in/kitchens/42/menu?veg=1:../img/logo.png,/api/menu,?page=2,#reviews,//cdn.example.com/x.js. Which one is the most common source of broken links when an app is deployed under a sub-path? - Why is building URLs by string concatenation a bug, and what do you use instead in JavaScript and in Java?
T5. Origins and sites
- What is an origin? Using P3, which of these share an origin with
https://tiffinbox.in/menu:https://tiffinbox.in:443/orders?id=7,http://tiffinbox.in/menu,https://api.tiffinbox.in/menu,https://tiffinbox.in:8443/? - What is a site (registrable domain, eTLD+1), and a schemeful site? Are
https://app.tiffinbox.inandhttps://api.tiffinbox.insame-origin? Same-site? What abouthttps://tiffinbox.github.ioandhttps://evil.github.io, and why? - Which browser behaviours are scoped to the origin and which to the site?
T6. Browsing contexts, documents and navigation
- What are a browsing context / navigable, a document and a window? How many of each exist for a tab showing a page with two iframes, after navigating twice?
- What does navigation do (to the document, JavaScript state, and history), and how do
location.assign,location.replace,history.pushStateand changinglocation.hashdiffer? - What is the back/forward cache (bfcache), what makes a page ineligible (the chapter's lab found an
unloadhandler), and why does it matter for users?
T7. Loading and script order
- P4 loaded a page with an inline script in the head,
defer d.js,async a.js,type="module" m.js, a slow (500 ms) classic script in the body, an inline script after it, and logged the order. Explain why the order was: inline head (20 ms), async (31 ms), slow classic (530 ms), inline body (530 ms, sees#p1but not#p2), defer, module,DOMContentLoaded,load. - When would you use each script type, and why does putting a classic
<script src>in the<head>withoutdeferhurt? - What do
preload,preconnectandfetchprioritydo, and when do they help or hurt?
T8. The DOM, attributes, properties and the other trees
- P8 set
input.value = 'roti'on<input value="dal">: the attribute stayeddalwhile the property becameroti. A checkbox unchecked by script kept itscheckedattribute.a.getAttribute('href')wasmenu?veg=1whilea.hrefwas absolute. Explain attributes versus properties, and the bug "my form reset puts back the old value". - What's the CSSOM, and why does reading
element.offsetHeightright after changing a style force layout? Give the name of this performance problem. - P9's accessibility snapshot listed
button "Order"for<button>but onlytext: Orderfor<div onclick>. What is the accessibility tree, who uses it, and what does thedivlack?
T9. The JavaScript runtime in the page
- P11 logged: sync start, sync end,
promise.then,queueMicrotask,setTimeout 0,requestAnimationFrame. Explain the event loop: tasks, microtasks, rendering steps, and why the order is exactly this. - What happens to the page when a click handler runs a 2-second loop? What happens with a
while (true)loop inside a promise chain of microtasks? - How do Web Workers give parallelism without data races on the DOM, and how does that compare with Volume 1, chapter 08's threads?
T10. Storage
- Compare cookies,
localStorage,sessionStorage, IndexedDB and the Cache API on: size limits, sync vs async, what's sent to the server, lifetime, and scope. P6 measured thatlocalStorageaccepted 5,200,000 characters beforeQuotaExceededError, thatgetItemaftersetItem('count', 5)returns a string, and a quota estimate of 2.1 GB. - Where should TiffinBox keep: the session token, the cart, the user's theme preference, a cached menu for offline use, and 200 order-history records for search?
- Why can storage disappear (eviction, Safari's 7-day rule, private browsing, storage partitioning in third-party iframes), and what does the app need to do about it?
T11. The same-origin policy and CORS
- P5 fetched
http://localhost:8002/api/menufrom a page onhttp://localhost:8001: without CORS headers,fetchfailed withTypeError: Failed to fetch; withAccess-Control-Allow-Origin: http://localhost:8001, it succeeded; inmode: 'no-cors'it returned an opaque response (typeopaque, status 0, empty body). Did the request reach the server in the first case? What exactly does the same-origin policy protect? - What makes a request "simple" versus preflighted? Walk through a preflight for
PUT /api/cartwithContent-Type: application/jsonand anAuthorizationheader. - Why is
Access-Control-Allow-Origin: *withAccess-Control-Allow-Credentials: truenot allowed, and why is reflecting the request'sOriginheader back unconditionally a vulnerability? - Why doesn't CORS protect your API from attackers using curl?
T12. Cookies, CSRF, XSS, CSP and isolation
- Explain each cookie attribute:
Secure,HttpOnly,SameSite=Strict|Lax|None,Domain,Path,Max-Age, and the__Host-prefix. Which combination should a session cookie use? - What is CSRF, why did
SameSite=Lax(the browsers' default since around 2020) largely defuse it, and what remains (same-site attacks from a subdomain, GET requests that change state)? - What is XSS, why is it the most damaging web vulnerability, and how does a Content Security Policy limit it? P10 showed a CSP of
script-src 'self'blocking an injected inline script with a console message. - What do
X-Frame-Options/frame-ancestors, COOP, COEP and Site Isolation each protect against?
Programming exercises
P1. Your first three pages, done properly
Following the Start Here chapter, build three pages: (1) a static document (a kitchen's About page) using semantic HTML only; (2) the same page with a stylesheet and a small script that toggles "Show opening hours"; (3) a menu page that fetches menu.json with fetch, renders it, and shows a loading state and an error message when the fetch fails. Then deliberately break each in one way (an unclosed tag, a CSS typo, a script error, a 404 for menu.json, a JSON syntax error) and write down what the browser does and where DevTools reports it.
P2. Take URLs apart and put them together
In the browser console, use new URL() to print the origin, host, pathname, search and fragment of five URLs including https://bücher.example/a b?q=₹ 5#top; resolve five relative references against https://tiffinbox.in/kitchens/42/menu?veg=1; and build https://tiffinbox.in/search?q=<user input>&city=Hyderabad safely for the input dal & roti #1 + extra. Show what naive concatenation produces instead.
P3. An origin and site calculator
Write a JavaScript function relation(a, b) that returns "same-origin", "same-site" or "cross-site" for two URLs, using new URL().origin for origins and a small hard-coded public-suffix list (in, com, co.uk, github.io) for sites, including the scheme (schemeful site). Test it on the T5 pairs plus https://tiffinbox.github.io vs https://evil.github.io and https://shop.example.co.uk vs https://blog.example.co.uk. Then explain why real code should use the full Public Suffix List (and where browsers get it).
P4. Script loading order
Build P4's page (inline head script, defer, async, type="module", a slow classic script in the body served with a 500 ms delay, an inline script after it, and DOMContentLoaded/load listeners) with a log function that records performance.now(). Predict the order, then run it. Then move the slow script to defer and compare when DOMContentLoaded fires.
P5. The same-origin policy from both sides
Serve one folder on http://localhost:8001 and another server on http://localhost:8002 with two endpoints: /api/menu (no CORS headers) and /api/cors (with Access-Control-Allow-Origin: http://localhost:8001). From a page on 8001, fetch both, and fetch('/api/menu', {mode: 'no-cors'}); print the result or error, and the response type and status. Check the 8002 server's log to see which requests arrived. Then add a PUT with Content-Type: application/json to /api/cors and observe the preflight in the Network panel.
P6. Storage limits and types
In the console, fill localStorage with 100,000-character strings until it throws, report how many characters fit and the error name, then clear it. Show that localStorage.setItem('count', 5) gives back the string "5" and that setItem('cart', {a: 1}) stores "[object Object]". Call navigator.storage.estimate(). Write a small IndexedDB store for orders with an index on kitchenId, add 200 orders, and query by kitchen. Measure how long a 2 MB localStorage.setItem blocks the main thread compared with an IndexedDB put.
P7. Frames, windows and postMessage
From a page on 8001, embed an iframe from 8002. Try to read frame.contentWindow.document.title and report the error. Then implement a safe postMessage exchange: the parent sends "hello" to the frame with an explicit target origin, the frame replies to event.source with event.origin as the target, and both sides check event.origin against an allow-list before using event.data. Finally, show what goes wrong if the frame uses "*" as the target origin and the parent page is replaced by an attacker's.
P8. Attributes versus properties
For <input value="dal">, <input type="checkbox" checked>, <a href="menu?veg=1"> and <div data-kitchen-id="42" class="card hot">: change the input's value and uncheck the checkbox with properties, then print each attribute, property and default (defaultValue, defaultChecked), a.href, dataset and classList. Then call form.reset() with the input inside a form and explain the result.
P9. Read the accessibility tree
Make a page with a <button>Order</button>, a <div onclick="…">Order</div>, an <input> with no label, the same input with a <label>, an <img> without alt and one with alt. Inspect them in DevTools' Accessibility pane (or the full-page accessibility tree view), and with Playwright's locator.aria_snapshot() (or getByRole queries). Then fix the div so it's a real button.
P10. Cookies and CSP from the server side
With a small server, send Set-Cookie: sid=abc123; HttpOnly; Path=/ and Set-Cookie: theme=dark; Path=/, then compare document.cookie with the cookies in DevTools' Application panel. Serve a page with Content-Security-Policy: script-src 'self' and try to inject an inline script with document.createElement('script'). Then switch the header to Content-Security-Policy-Report-Only with a report-to/report-uri endpoint and log the reports.
P11. Tasks, microtasks and a frozen page
Reproduce P11's order (setTimeout 0, Promise.then, queueMicrotask, requestAnimationFrame, synchronous logs). Then add a button whose click handler busy-waits 2 seconds while a CSS animation runs, and observe the frozen animation and the long task in DevTools' Performance panel. Finally, split the 2 seconds of work into 50 ms chunks with await new Promise(r => setTimeout(r, 0)) (or scheduler.yield()) and compare responsiveness, then move the work to a Web Worker.
Cumulative projects (chapters so far: Volume 1, and Volume 2's 00 and 12)
C1. Trace one page load end to end
Pick a real page (TiffinBox's equivalent: a food-delivery site's restaurant page). Using curl -w timings, dig, openssl s_client, DevTools (Network waterfall, Performance panel) and the Application panel, write a report that follows one load through every layer of Volume 1 and this chapter: DNS (records, TTLs), TCP and TLS (round trips, protocol, certificate chain), HTTP (version, compression, caching headers, cookies sent), the document's loading (render-blocking resources, script types, preloads), the main thread (long tasks), storage written, third-party origins contacted and what each was allowed to do (CORS, cookies' SameSite, CSP). End with the three changes that would most improve the page and the evidence for each.
Combines: CLI tools (Vol 1 ch 01); bytes and encodings (ch 06); latency numbers (ch 07); processes and the browser's process model (ch 08); DNS, TCP, TLS and HTTP (ch 09); parsing and JIT for JavaScript (ch 10); this chapter's loading, storage and security model.
C2. A secure, offline-tolerant menu page
Build a TiffinBox menu page with a small Java backend (Volume 1, chapter 09's C1 server or any framework): the page loads the menu from /api/kitchens/{id}/menu (same origin), lets the user filter by price and veg with URL query parameters kept in sync via history.replaceState, adds items to a cart stored in IndexedDB, and works offline with the last cached menu (stored with a timestamp and shown as "Updated 2 hours ago"). Security: the session cookie is __Host-, HttpOnly, Secure, SameSite=Lax; all output uses textContent; the backend sends a strict CSP, frame-ancestors 'none', and validates every input; a review text containing <img src=x onerror=alert(1)> must display harmlessly. Write tests for the XSS case, the offline case and the URL round trip.
Combines: HTTP servers, headers and caching (Vol 1 ch 09, 11); input validation and parsing (ch 02, 10); data structures for the cart (ch 03); money in paise (ch 06); concurrency between tabs (ch 08); this chapter's URLs, history, storage, CSP and cookies.
C3. Choose where a feature runs: browser, server or both
TiffinBox wants three features: (a) live search of dishes as you type across 50,000 dishes; (b) an estimated delivery time on the menu page; (c) "your usual order" suggestions. For each, decide what runs in the browser and what on the server, considering data size and freshness, latency (Volume 1, chapter 07 and 09 numbers), privacy and security (what must be trusted), offline behaviour, battery and CPU on low-end phones, and the event loop (T9). Write a one-page decision for each with a sequence diagram in words.
Combines: data structures and indexes (Vol 1 ch 03, 11's file indexer); algorithms and complexity (ch 04); probability and estimates (ch 05); payload sizes and compression (ch 06); latency hierarchy (ch 07); concurrency and workers (ch 08); networking costs (ch 09); runtime performance of JS (ch 10); this chapter's storage, event loop and security model.
What the chapter leaves out
HTTP caching in the browser
The browser's HTTP cache decides whether most of a page load touches the network at all. Know Cache-Control (max-age, no-cache meaning "revalidate", no-store meaning "don't store", immutable, stale-while-revalidate), validators (ETag with If-None-Match, Last-Modified with If-Modified-Since, giving 304 responses), and the standard pattern: hashed asset file names (app.3f9a1c.js) with max-age=31536000, immutable, and the HTML document with no-cache so deploys take effect immediately. The cache is partitioned by top-level site (a CDN script cached for site A isn't reused for site B), which ended the "use a public CDN so it's already cached" argument. Chapter 31 goes further.
The rendering pipeline's threads and processes
Chapter 18 covers browser internals in depth, but one idea belongs here: a modern browser is a multi-process system (Volume 1, chapter 08): a browser process (UI, network, storage), a GPU process, and renderer processes per site (Site Isolation), each with a main thread (DOM, JavaScript, style, layout) and a compositor thread (scrolling and transform/opacity animations). That's why a blocked main thread can still scroll smoothly (P11's transform surprise), why a crashing tab doesn't take the browser down, and why memory use grows with the number of sites open.
Permissions, user activation and powerful features
Many APIs (notifications, geolocation, camera, clipboard read, fullscreen, pop-ups, autoplay with sound, navigator.share, Web Bluetooth) require a secure context (HTTPS or localhost), a permission the user grants, and often transient user activation (the call must happen in response to a click or key press, within a short window). Prompting on page load gets denied and permanently blocked; ask in context, after explaining why. The Permissions Policy header lets a site disable features for itself and its iframes (Permissions-Policy: camera=(), geolocation=(self)), a useful security control for pages that embed third parties.
Fetch Metadata and defence in depth on the server
Browsers send Sec-Fetch-Site (same-origin, same-site, cross-site, none), Sec-Fetch-Mode (navigate, cors, no-cors…), Sec-Fetch-Dest (document, script, image…) and Sec-Fetch-User with every request. A server can use them for a resource isolation policy: reject cross-site requests to APIs except top-level navigations, which blocks CSRF, cross-site script inclusion and many side-channel attacks in a few lines of middleware, independently of cookies' SameSite. Combined with CSP, COOP, CORP, HSTS and X-Content-Type-Options: nosniff, these headers are cheap, high-value hardening that belongs in every backend's default configuration.
Standards, compatibility and feature detection
The web platform is defined by living standards (WHATWG's HTML, DOM, Fetch and URL standards; W3C's CSS and accessibility specs; TC39's ECMAScript), implemented by three engines (Chromium's Blink, Firefox's Gecko, Safari's WebKit; every iOS browser uses WebKit). Features ship at different times: check MDN's browser compatibility tables and caniuse.com, follow the Baseline status ("widely available"), detect features at run time ('serviceWorker' in navigator) rather than sniffing user agents, and test in all three engines (Playwright runs Chromium, Firefox and WebKit). Your users' browser mix (in India, a large share of Android Chrome and in-app WebViews) should drive which features you rely on.
WebViews and in-app browsers
Links opened inside social or messaging apps often load in an in-app browser or WebView, not the user's browser: different cookie jars (users appear logged out), limited storage and APIs, sometimes injected scripts, and older engine versions on some Android devices. Payment and login flows (OAuth, UPI intents) behave differently there; test them in the in-app browsers your users actually come from, and provide "Open in browser" paths for flows that need the real one.
Senior exercises
S1. Diagnose "users are randomly logged out"
After moving the API from tiffinbox.in/api to api.tiffinbox.in, some users report being logged out randomly; it's worse on iPhones and inside a messaging app's in-app browser. Using origins, sites, cookies and storage partitioning, list the hypotheses, the evidence for each, and the fix.
S2. Review a frontend PR for platform-level bugs
A PR adds a "share your order" feature: it builds a link with 'https://tiffinbox.in/share?order=' + order.id + '¬e=' + note, stores the auth token in localStorage "so the share page can read it", renders the note on the share page with innerHTML, opens the share page with window.open(link) and listens for message events from it without checking the origin, and sets Access-Control-Allow-Origin: * on the share API "to make it work". Write the review, ranked by severity.
S3. Set the security header baseline for every service
Write the default HTTP response header policy for TiffinBox's web-facing services (HTML pages and JSON APIs), with each header's value, what it protects, and how to roll it out without breaking things. Include CSP, HSTS, cookies, CORS, frame-ancestors, COOP/COEP/CORP, Referrer-Policy, Permissions-Policy, X-Content-Type-Options and Fetch Metadata checks.
S4. Decide between a single-page app and server-rendered pages
TiffinBox is rebuilding its customer website. One team proposes a client-rendered SPA (React, all rendering in the browser after loading a JS bundle); another proposes server-rendered HTML with progressive enhancement and small islands of interactivity. Compare them using this chapter's concepts (loading and script order, navigation and history, bfcache, the main thread, storage, security model, accessibility tree) and Volume 1's latency numbers, for users on mid-range Android phones on 4G in Indian cities. Recommend and justify.
S5. Make a third-party widget safe to embed
TiffinBox wants to embed a third-party chat-support widget and a payment widget on its checkout page. Design how they're embedded: script tag versus iframe, sandboxing, CSP changes, communication with the page, data the vendors can access, failure behaviour if the vendor is slow or down, and the contractual and monitoring requirements.
S6. Teach "origin" in ten minutes
Prepare a ten-minute session for backend engineers who keep hitting CORS errors and "just add *". Plan the explanation, two live demos (from P5 and P10), the three rules they should leave with, and how you'll check they stuck.