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

JavaScript Execution Contexts in XSS

Understanding how injected scripts execute with the same privileges as legitimate page scripts.

JavaScript Execution Contexts in XSS

What you'll learn: You'll understand why injected JavaScript code is so powerful—it runs with the exact same privileges as the legitimate page scripts.

The Core Principle

When an attacker successfully injects JavaScript through XSS (whether reflected, stored, or DOM-based), that malicious code doesn't run in some isolated "bad script" sandbox. Instead, it executes in the same security context as all the legitimate JavaScript on the page. The browser cannot distinguish between trusted developer code and attacker-injected code—both have identical permissions and access.

What This Means in Practice

Think of it like giving someone your house key. Once they're inside, they can access everything you can: your refrigerator, your safe, your documents. The house doesn't know they weren't invited.

When injected JavaScript executes, it can:

  • Read all cookies (including session tokens, unless marked HttpOnly)
  • Access the DOM: read and modify any content on the page, including forms, hidden fields, and user data
  • Make HTTP requests on behalf of the user with their credentials
  • Execute with the page's origin: bypass Same-Origin Policy for that domain
  • Call any JavaScript functions already loaded on the page
  • Access local storage and session storage

The Browser's Blind Spot

The browser sees the script tag's source location (which domain served it) but once JavaScript is executing within a page's context, all scripts share the same privileges. An attacker's injected payload runs under the victim site's origin, meaning document.domain and all same-origin checks treat it as legitimate code.

This is why XSS is so devastating—it's not about breaking into the application from outside; it's about running malicious code from inside the trusted boundary.

Key Takeaway: Injected XSS payloads execute with full access to everything legitimate page scripts can access—there's no privilege separation once code is running in the page's JavaScript context.