What is XSS in JavaScript: Explanation and Example
XSS (Cross-Site Scripting) is a security vulnerability where attackers inject malicious scripts into web pages viewed by others. These scripts run in the victim's browser, potentially stealing data or performing unwanted actions.How It Works
Imagine you visit a website that lets users write comments. If the website does not check what users type, a bad person could add a secret script instead of a normal comment. When you open the page, your browser runs that secret script without you knowing.
This happens because the website mixes user input directly into its pages without cleaning it. The browser trusts the page and runs all scripts it finds, including the bad ones. This is like inviting a stranger into your house and letting them do anything they want.
Attackers use XSS to steal information like passwords or to trick you into clicking things you didn’t want to. It’s important for websites to block this by checking and cleaning user input before showing it.
Example
This example shows how a simple comment box can be unsafe if it allows scripts.
const userInput = '<script>alert("XSS Attack!")</script>'; // Unsafe way: directly adding user input to page const commentSection = document.createElement('div'); commentSection.innerHTML = userInput; document.body.appendChild(commentSection);
When to Use
XSS is not something to use but something to prevent. Web developers must be careful when showing user input on pages. Always clean or escape input before adding it to HTML.
Real-world cases include comment sections, chat apps, or any place users can add text. If not protected, attackers can steal cookies, hijack accounts, or spread malware.
Key Points
- XSS lets attackers run harmful JavaScript in other users’ browsers.
- It happens when user input is added to pages without cleaning.
- Always sanitize or escape user input to prevent XSS.
- Common targets are comment boxes, forms, and chat messages.