Course contentsShow
← Security
Lesson 637 of 3,05214. Web Security - XSS and Content InjectionFree lesson

XSS in Different Contexts: HTML, JavaScript, CSS

Recognizing how XSS manifests differently in HTML attributes, JavaScript strings, and CSS contexts.

XSS in Different Contexts: HTML, JavaScript, CSS

You'll learn: How XSS attacks change dramatically based on where your malicious payload lands—HTML, JavaScript code, or CSS—and why context matters for successful exploitation.

Why Context is Everything

Imagine trying to break out of three different rooms: one with a door, one with a window, and one with only a ventilation shaft. Each requires a completely different escape strategy. XSS works the same way—your attack payload must match the context where it's injected.

HTML Context

When user input appears directly in HTML content, you typically inject tags:

Vulnerable pattern:

<div>Welcome, [USER_INPUT]</div>

Attack payload:

<script>alert('XSS')</script>

You're breaking into the structure by adding new HTML elements.

JavaScript Context

When input lands inside JavaScript code (like in a string), you need to escape the string first:

Vulnerable pattern:

<script>
var name = '[USER_INPUT]';
</script>

Attack payload:

'; alert('XSS'); //

You're closing the string, adding your own code, then commenting out the rest.

CSS Context

When input appears in CSS (styles or style attributes), you can inject malicious CSS:

Vulnerable pattern:

<div style="color: [USER_INPUT]">Text</div>

Attack payload:

red; background:url('javascript:alert(1)')

Different browsers have different CSS-based attack vectors, often using expressions or URL schemes.

The Critical Difference

Each context has different special characters and syntax rules. An HTML payload won't work in JavaScript context because the characters are interpreted differently. You must understand where your input lands to craft the right escape sequence.

Key Takeaway: XSS exploitation requires context-aware payloads—what works in HTML (<script>) won't work in JavaScript strings (need ';), and CSS contexts have their own unique attack vectors. Always identify the injection context first.