Cross-Site Scripting: The Mechanism
Browsers execute scripts that arrive with a page. Cross-site scripting (XSS) is the condition where an attacker controls content that the browser treats as executable script. The browser has no way to distinguish attacker-supplied script from developer-supplied script once both are embedded in the same document.
The name is historical. Early cases involved loading content from a different site to bypass access controls. The term stuck even though most XSS today does not require cross-site resource loading.
The Browser Trust Model
Browsers enforce the same-origin policy (SOP): a script running at example.com cannot read data from bank.com. This isolation applies to resources fetched from other origins.
XSS bypasses SOP by operating inside the target origin. If an attacker's script runs on bank.com, it runs with the same permissions as any legitimate script on bank.com. It can read cookies scoped to bank.com, make authenticated requests to bank.com APIs, and read DOM content rendered on bank.com pages. SOP does not protect against this because the script is not cross-origin; it is the victim origin.
The attacker's problem is getting their script into the target origin's document. That is what XSS vulnerabilities allow.
How Injection Happens
HTML documents mix markup, data, and script. When an application takes input from a user or external source and places it into a document without distinguishing data from markup, an attacker can supply input that the browser parses as markup or script rather than data.
A server rendering a search term directly into a response:
You searched for: [user input]
If the user input is <script>alert(1)</script> and the server places it verbatim into the HTML, the browser parses a <script> element and executes it. The server intended to display text; the browser executed code.
The same problem exists in HTML attributes, JavaScript strings, URLs, CSS, and JSON embedded in HTML. Each context has its own parsing rules and its own set of characters that terminate the current context and begin another.
Three Categories
XSS falls into three categories based on how the injected script reaches the browser:
Reflected XSS: the application takes input from the current request and includes it in the response without storing it. The attack requires the victim to follow a crafted URL.
Stored XSS: the application stores attacker-controlled input and later includes it in responses served to other users. No crafted URL is needed once the payload is stored.
DOM-based XSS: client-side JavaScript reads attacker-controlled data and writes it to the DOM without server involvement. The server response may be entirely safe; the vulnerability is in the JavaScript.
Each category has different persistence, reach, and mitigation requirements.