Cross-Site Scripting
By Malcolm McDonald Founder, Editor-in-ChiefAuthor of Grokking Web Application Security
If your site allows users to add content, you need to be sure that attackers cannot inject malicious JavaScript.
- Prevalence
- Common
- Exploitability
- Easy
- Impact
- Harmful
What is cross-site scripting (XSS)?
Cross-site scripting (XSS) is an injection attack in which an attacker gets malicious JavaScript to run in other users' browsers. In stored XSS the script is saved on your site, for instance in a comment, and runs for everyone who views it. Attackers use it to steal session cookies, capture keystrokes and impersonate users.
What you'll learn
- How a script saved in user content runs for everyone who views it
- How attackers use injected JavaScript to steal session cookies
- How escaping, HTML sanitization and a Content Security Policy prevent XSS
Where this lesson counts
OWASP Top 10
Untrusted input reaches an interpreter as part of a command or query, including SQL, OS and cross-site scripting.
OWASP 2025 folds cross-site scripting into Injection: untrusted input reaching the HTML interpreter.
Learn more about A05PCI DSS v4.0.1
Requirement 6.2.4: engineering techniques must prevent injection, data-structure, cryptographic, business-logic and access-control attacks in bespoke software.
Learn more about 6.2.4Requirement 6.4.1: public-facing web applications must be protected against known attacks by regular vulnerability review or an automated technical solution.
Learn more about 6.4.1This lesson includes
Cross-Site Scripting lab
You run breddit.com, a forum for bakers. Watch Mal post a comment containing a script tag that runs in Vic's browser when he opens the thread, then see how a real attack would redirect Vic and hand his cookies to a site Mal controls.
How to prevent Cross-Site Scripting
The prevention guide covers four approaches, including:
- Escape Dynamic Content
- Allowlist Values
- Implement a Content Security Policy
Cross-Site Scripting quiz
Two questions. Passing marks the lesson complete.
Sources
- CSP (Content Security Policy) MDN
- Content security policy PortSwigger
- Cross-site scripting PortSwigger
Related lessons
Browse all 45 lessons
Reflected XSS
When building a website, you need to be sure you do not accidentally create a channel that allows malicious JavaScript to be bounced off your server.
DOM-based XSS
If you make use of URI fragments in your site, you need to ensure they cannot be abused to inject malicious JavaScript.
Cross-Site Request Forgery
If an attacker can forge HTTP requests to your site, they may be able to trick your users into triggering unintended actions.
CSS Injection
Attackers can manipulate user-generated CSS to extract sensitive data.