Cross-site scripting (XSS) happens when a website shows user input on a page without making it safe first. If that input is JavaScript, the victim's browser runs it, as if the website itself had sent it.
Practise only in your lab or on legal training platforms.
Why it's dangerous
The script runs with the website's trust, so it can:
- read cookies that aren't
HttpOnlyand send them to the attacker, - show a fake login form on the real site,
- take actions as the logged-in user, like changing their email address.
The three types
Reflected. The script is in a link, like site.com/search?q=<script>...</script>. The page reflects it back once, to whoever opens that link.
Stored. The script is saved, for example in a comment, and runs for every visitor who views it. This is the most dangerous kind.
DOM-based. The server is fine, but the page's own JavaScript takes something like the URL and writes it into the page unsafely.
Try it in DVWA
With DVWA security set to low:
- Open XSS (Reflected) and enter your name. It's shown back to you.
- Now enter:
<script>alert('XSS')</script>
A pop-up appears. The page ran your script.
- Open XSS (Stored), post the same script as a guestbook message, then reload. It runs again, and it would run for anyone visiting.
How sites defend against it
- Encode output. Show
<as<so the browser displays it as text instead of running it. Modern frameworks like React and Django do this by default, until a developer switches it off. - Content-Security-Policy. A response header that tells the browser which scripts are allowed to run.
- HttpOnly cookies. Even if XSS happens, the session cookie can't be read by script.
alert()is only a harmless way to prove a script ran. In real attacks, nothing visible happens at all.