#Why this matters
Just as SQL injection happens when user data is parsed as database code, Cross-Site Scripting (XSS) happens when untrusted data is parsed as browser code. When a web page inserts input into HTML, attributes, URLs, or JavaScript without proper escaping, the browser treats that data as executable markup or script.
Because the injected script runs inside the victim's browser under the site's origin, the Same-Origin Policy treats it as trusted application code. It can read the DOM, steal anti-CSRF tokens, send authenticated fetch() requests, and access cookies that lack HttpOnly. Even with HttpOnly, the script can still perform actions inside the victim's session.
#Three ways XSS reaches the browser
XSS falls into three types based on where input is stored and how it reaches the browser.
| Type | Where payload lives | How it triggers | Visible in server logs |
|---|---|---|---|
| Reflected | URL parameter, form field, or header in one request | Victim opens a crafted link or form | Yes |
| Stored | Database, profile, or log entry on the server | Any user or admin views the rendered page | Yes, on submission |
| DOM-based | Client-side source (location.hash, location.search) |
Browser JS writes the source to a sink | Not always (fragments stay local) |
In reflected and stored XSS, the server's response already contains the untrusted payload. In DOM-based XSS, the server delivers a static page, and client-side JavaScript copies a controllable source into an unsafe sink. Fragments after # (location.hash) stay in the browser and never reach server logs or WAFs.
In veb-tahlil labs, a simulated admin bot often visits a submitted URL or saved post. Knowing what the bot executes and whether HttpOnly or CSP blocks access is central to both testing and defence.
#Contexts, sources, and sinks
Testing begins by finding where input lands, not by pasting one payload everywhere. Sending a harmless canary like probe99 lets you inspect the surrounding syntax in Browser DevTools or Burp Suite Repeater.
Each execution context breaks out differently:
- HTML body: Between element tags, angle brackets (
<,>) open a new element such as animgelement with anonerrorattribute or an inlinescriptelement. - Quoted attribute: Inside
value="probe99", angle brackets stay inside the string until you close the double quote ("), then add an event handler such asonfocuswithautofocus, or close the element. - URL and JS contexts: Inside
href,javascript:alert(1)runs on click even when<,>, and quotes are HTML-encoded. Inside a JavaScript string literal, closing the quote breaks into code execution without angle brackets. - DOM sink: Even on a static page, JavaScript can read a source (
location.search,location.hash,document.referrer) and pass it to an unsafe sink (innerHTML,outerHTML,document.write(),eval()).
// Vulnerable DOM flow: source -> sink
const params = new URLSearchParams(location.search);
document.getElementById("greeting").innerHTML = "Hello, " + params.get("name");
document.getElementById("profile-link").setAttribute("href", params.get("next"));$ curl -s "http://lab.local/search?q=probe99%3C%3E%22%27" | grep probe99
search_value = value="probe99<>"'"Here < and > were encoded as < and >, blocking a new element tag. However, the raw double quote " inside value="..." still lets an attacker break out and inject " onfocus="alert(1)" autofocus=".
#Defending against XSS
Effective defence treats untrusted input strictly as data across both server templates and browser JavaScript.
- Context-aware output encoding: Encode right before rendering for the exact context. Use HTML entity encoding (
<,>,&,",') for HTML text and quoted attributes. For links (href,src), enforce anhttp:orhttps:allow-list sojavascript:anddata:URLs are rejected. Template engines (Jinja2 autoescape, React JSX) encode HTML text and attributes by default unless bypassed with|safeordangerouslySetInnerHTML. - Safe DOM APIs: Avoid
innerHTML,outerHTML,document.write(), andeval(). UsetextContentorinnerTextso the browser inserts literal text.
// Safe text insertion and URL allow-list check
const params = new URLSearchParams(location.search);
document.getElementById("greeting").textContent = "Hello, " + (params.get("name") || "guest");
const parsed = new URL(params.get("next") || "/", location.origin);
if (parsed.protocol === "http:" || parsed.protocol === "https:") {
document.getElementById("profile-link").setAttribute("href", parsed.href);
}- HTML sanitization: When users must submit formatted HTML, clean it with a maintained sanitizer such as DOMPurify rather than custom regexes.
- Defence in depth: Set
HttpOnlyandSameSiteon session cookies to blockdocument.cookiereads, and enforce a strict Content Security Policy (default-src 'self'; script-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'self') withoutunsafe-inlineorunsafe-eval.
#Common mistakes
- Keyword blocklists: Stripping the word
scriptfails against event handlers onimg(onerror) orsvg(onload) elements, mixed case, or nested strings. - Relying on
HttpOnlyalone: Even whendocument.cookieis hidden, an XSS payload still runs inside the authenticated session and can sendfetch()requests as the victim. - Wrong-context encoding: HTML-encoding quotes does not stop
javascript:alert(1)inside anhrefattribute, nor is it safe inside inline JavaScript variable assignments. - Ignoring DOM sinks: Server-side escaping does not protect client scripts that read
location.hashand assign directly toinnerHTML.
#Summary
- Reflected, stored, and DOM-based XSS execute untrusted JavaScript inside a victim's browser under the site's origin.
- Probe with a benign canary first to identify the exact HTML, attribute, URL, or JS context, and trace sources to DOM sinks.
- Prevent XSS with context-aware output encoding, URL allow-lists, and safe DOM APIs like
textContent, reinforced byHttpOnlycookies and a strict CSP.