JavaScript > Security > Common Vulnerabilities > Cross-Site Scripting (XSS)

Demonstrating XSS via Unsafe HTML Injection

This code snippet demonstrates a common XSS vulnerability where user input is directly injected into the HTML of a page without proper sanitization. This can allow malicious scripts to be executed in the user's browser.

Code Example: Vulnerable Greeting Function

This code snippet defines a `displayGreeting` function that takes a username as input and injects it directly into the HTML of an element with the ID 'greeting'. It then attempts to retrieve the username from the URL parameters. If a malicious user provides a username containing JavaScript code (e.g., ``), this code will be executed when the `displayGreeting` function is called. The `innerHTML` property directly renders the string, which allows the browser to interpret and execute any included scripts.

// WARNING: This code is vulnerable to XSS!
function displayGreeting(username) {
  document.getElementById('greeting').innerHTML = 'Hello, ' + username + '!';
}

// Simulate getting username from a URL parameter (e.g., ?username=<script>alert('XSS')</script>)
const urlParams = new URLSearchParams(window.location.search);
const username = urlParams.get('username');

// Display the greeting (vulnerable to XSS)
displayGreeting(username);

Concepts Behind the Snippet

This vulnerability arises because the code trusts user-supplied data without validating or sanitizing it. The `innerHTML` property is a powerful tool for manipulating the DOM, but it can also be dangerous if used with untrusted data. Browsers interpret any `