Cybersecurity

What is Cross-Site Scripting (XSS)?

Cross-site scripting is an attack where malicious scripts are injected into trusted web pages and run in other users' browsers.

Cross-Site Scripting (XSS) is a web vulnerability where an attacker injects malicious JavaScript into a page that other users view. When the victim's browser runs that script, it can steal cookies, hijack sessions, or manipulate the page — all under the trust of the legitimate site.

How It Works:

  1. An attacker finds an input that gets shown to other users unescaped
  2. They inject a <script> or event handler
  3. The site stores or reflects that input into a page
  4. Victims load the page and their browser runs the attacker's code

Types of XSS:

  • Stored: Malicious script saved on the server (e.g. in a comment)
  • Reflected: Script bounced back via a URL or form
  • DOM-based: Vulnerability in client-side JavaScript handling

How to Prevent It:

  • Escape output: Encode user data before rendering
  • Sanitize input: Strip dangerous HTML
  • Content Security Policy (CSP): Restrict what scripts can run
  • Use frameworks: Modern frameworks escape by default

FAQ

Why is XSS so dangerous?

Because the malicious code runs with the victim's privileges on a trusted site. It can read cookies, act as the user, capture keystrokes, or redirect them to phishing pages.

How is XSS different from SQL injection?

XSS targets the browser by injecting scripts into pages. SQL injection targets the database by injecting queries. Both stem from trusting unvalidated input, but they attack different layers.

Promote your content

Reach over 400,000 developers and grow your brand.

Join our developer community

Hang out with over 4,500 developers and share your knowledge.