# Cross-Site Scripting (XSS)

> An attack that hides a script in a page. It runs for everyone who visits.

**Field:** Software Development  
**Category:** Security  
**Also known as:** XSS, XSS Attack, Script Injection, Stored XSS, Reflected XSS, DOM-based XSS

## Think of it like

Think of it like a fake note pinned on a shop's board. Every shopper thinks it is real.

## Definition

Cross-site scripting gets a bad script to run on pages others visit. It happens when a site shows user text, like a comment, without making it safe first. The browser then treats the text as code. The script runs as if the site wrote it, so it can steal session cookies or act as the user. The fix is to escape all user text before showing it.

## Example

Emma's blog shows comments as raw HTML. Someone posts a comment with a script tag, and it runs for every reader who opens the post.

## Example code

```html
<p>Great post! <script>alert(1)</script></p>
```

If shown as raw HTML, the script runs for every reader.

## Why it matters

A script on your page can do anything the user can. One comment box can expose every account.

## Common mistake

Building HTML by joining strings with user text. Let the framework escape it, and never switch that off without care.

## Three principles

- **Text becomes code.** In the browser.
- **Runs as the site.** Steals or acts as users.
- **Escape on output.** Every piece of user text.

## Related terms

- [SQL Injection](https://learn.benibix.com/term/development/sql-injection)
- [Input Validation](https://learn.benibix.com/term/development/input-validation)
- [HTTP Cookie](https://learn.benibix.com/term/development/cookie)
- [Cross-Site Request Forgery (CSRF)](https://learn.benibix.com/term/development/cross-site-request-forgery)
- [Output Encoding](https://learn.benibix.com/term/development/output-encoding)
- [Content Security Policy (CSP)](https://learn.benibix.com/term/development/content-security-policy)

## Told apart from

- [XSS vs CSRF](https://learn.benibix.com/compare/xss-vs-csrf): Cross-site scripting and cross-site request forgery both abuse the trust between you and a site, in opposite ways. XSS puts the attacker's script on the real site, where it runs as if the site wrote it. CSRF stays on the attacker's page. It tricks your browser into sending a request to the real site. Safe output stops XSS. Tokens and SameSite cookies stop CSRF.

---

Source: https://learn.benibix.com/term/development/cross-site-scripting
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-19
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
