Cross-Site Scripting (XSS) is a type of web security vulnerability that allows attackers to inject malicious scripts—usually JavaScript—into webpages viewed by other users. It’s one of the most common and dangerous vulnerabilities found in web applications.
🧠 What Is Cross-Site Scripting?
- XSS occurs when a website fails to properly validate or sanitize user input, allowing attackers to insert scripts that run in other users’ browsers.
- These scripts can steal cookies, capture keystrokes, redirect users, or even take control of user accounts.
As MDN Web Docs explains, the browser executes the malicious code as if it came from the trusted site, making it especially deceptive.
🧬 Types of XSS Attacks
Type | Description |
---|---|
Reflected XSS | The malicious script is part of the URL or request and is reflected back in the response. Often used in phishing. |
Stored XSS | The script is saved on the server (e.g., in a comment or profile field) and runs whenever someone views the page. |
DOM-based XSS | The vulnerability exists in client-side JavaScript that dynamically updates the page without proper input handling. |
More details are available from PortSwigger’s Web Security Academy and OWASP’s XSS guide.
⚠️ Why It’s Dangerous
- Can hijack user sessions
- Steal sensitive data like login credentials
- Deface websites or redirect users to malicious sites
- Exploit browser vulnerabilities
Even major platforms like Facebook and YouTube have been targeted by XSS attacks.
🛡️ How to Prevent XSS
- Sanitize user input: Remove or escape potentially dangerous characters.
- Use Content Security Policy (CSP): Restrict what scripts can run.
- Validate input on both client and server sides.
- Avoid using
innerHTML
ordocument.write
with user data.
Let’s walk through a simple example of sanitizing user input to prevent XSS attacks—no code execution needed!
🧼 Basic Concept
Sanitization means removing or escaping characters that could be interpreted as code by the browser. This prevents malicious scripts from running.
🧪 Example: Unsafe vs Safe Display
❌ Unsafe (Vulnerable to XSS)
<div>
User comment: <span id="comment"></span>
</div>
<script>
const userInput = "<script>alert('XSS!')</script>";
document.getElementById("comment").innerHTML = userInput; // BAD!
</script>
This will execute the script and show an alert—classic XSS.
✅ Safe (Sanitized)
<div>
User comment: <span id="comment"></span>
</div>
<script>
const userInput = "<script>alert('XSS!')</script>";
const sanitized = userInput
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
document.getElementById("comment").innerHTML = sanitized; // SAFE!
</script>
Now the script is displayed as text, not executed.
🛡️ Pro Tip
Use libraries like:
- DOMPurify (JavaScript)
- OWASP Java Encoder (Java)
- htmlspecialchars() (PHP)
These tools handle sanitization more robustly and safely.