Concept Explanation
Imagine a guest comes to your house and leaves a "Post-it" note on your fridge. Normal Guest: Writes "Thanks for the coffee!" XSS Attacker: Writes a magic spell on the note that, when you read it, forces you to give them your house keys.
In JS, XSS happens when an attacker injects a <script> into your page. This script can steal the user's login cookies or redirect them to a fake bank website.
Syntax or Core Structure
The Danger
// DANGEROUS: If 'userInput' is " <script>steal()</script> ", it will run!
document.getElementById('welcome').innerHTML = userInput;
The Defense
// SAFE: This treats the input as literal text, not HTML
document.getElementById('welcome').innerText = userInput;
Best Practices
- Sanitize: Use a library like
DOMPurifyif you absolutely MUST render HTML from a user. - Content Security Policy (CSP): This is a browser feature that tells the website: "Only run scripts that come from MY server. Ignore all others."
- HttpOnly Cookies: Tell the browser: "Only the server can read this cookie. JavaScript is not allowed to touch it." This stops 90% of token theft.
Practice Exercises
- The Sanitizer: Write a small function that replaces
<with<and>with>in a string. - The CSP Explorer: Look at the "Network" tab on a site like Facebook. Find the
content-security-policyheader and try to understand one part of it. - The Cookie Policy: Research what the
SameSite=Strictflag does for cookies.