Cross-Site Scripting (XSS) occurs when an application includes malicious script code in web pages sent to visitors without proper sanitization, allowing attackers to hijack sessions.

1. Main XSS Types

  • Stored XSS: The exploit payload is permanently saved in database tables (like user comments) and executed every time users load the page.
  • Reflected XSS: The payload is passed via parameter URLs and executed immediately when the page reflects the parameters back.

2. Mitigation: Context-Aware Output Encoding

To secure pages, treat all dynamic text variables as plain text rather than active HTML. Use HTML sanitization libraries and output encoding methods before rendering variables.

Secure JavaScript code:

document.getElementById("output").textContent = userInput;