# Cross-Site Scripting (XSS): A Complete Attack and Defense Guide
## Introduction to XSS
Cross-Site Scripting (XSS) is a client-side code injection attack where attackers inject malicious scripts into trusted websites. When successful, XSS allows attackers to execute arbitrary JavaScript in the victim browser, potentially compromising accounts, stealing data, or performing actions on behalf of users.
XSS vulnerabilities occur when web applications include untrusted data in web pages without proper validation or escaping. Attackers use various techniques to inject malicious scripts that appear legitimate to the browser.
## Types of XSS Attacks
### Reflected XSS (Non-Persistent)
The malicious script comes from the current HTTP request. The vulnerable application includes unvalidated input from requests in immediate responses.
Example: https://target.com/search?q= where the server reflects the script without sanitization and the browser executes it when the page loads.
### Stored XSS (Persistent)
The malicious script is stored on the server (database, message forum, comment field). Every user accessing the affected page executes the script.
Example: User submits comment with script content like . The server stores the script in database and every user viewing this comment executes the script.
### DOM-Based XSS
The vulnerability exists in client-side code rather than server-side code. The attack payload is executed by modifying the DOM environment in the victim browser.
Example: Vulnerable JavaScript like document.write(document.URL.substring(position, document.URL.length)) when manipulated with URL fragment like https://target.com/page.html?item= causes the browser to write the script to the page.
## XSS Attack Consequences
### Session Hijacking
Steal session cookies with script that captures document.cookie and sends it to attacker server.
### Credential Theft
Inject fake login forms that appear as legitimate session expiry prompts to capture usernames and passwords.
### Keylogging
Capture all keystrokes using document.addEventListener('keypress') to record user input.
### Defacement
Modify page content and styles using document.body.innerHTML or document.body.style properties.
## Practical XSS Exploitation
### Finding XSS Vulnerabilities
Test all input points systematically with basic test payloads like ,
, and
Ethical Hacking
Cross-Site Scripting (XSS): A Complete Attack and Defense Guide
Complete XSS attack guide covering stored, reflected, and DOM-based XSS. Learn exploitation techniques, cookie stealing, bypass methods, and comprehensive prevention strategies.

Amit KumarEthical Hacker & Founder
5 min read
