JAVASCRIPT

Preventing XSS with Contextual Output Encoding (JavaScript)

Prevent Cross-Site Scripting (XSS) attacks in JavaScript by correctly encoding user-generated content based on its display context (HTML, attribute, URL, etc.).

/**
 * Escapes HTML entities in a string to prevent XSS when inserting into HTML content.
 * @param {string} str The string to escape.
 * @returns {string} The escaped string.
 */
function escapeHtml(str) {
  const div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
}

/**
 * Escapes a string for use within an HTML attribute (e.g., value="...").
 * @param {string} str The string to escape.
 * @returns {string} The escaped string.
 */
function escapeHtmlAttribute(str) {
  return str.replace(/&/g, '&')
            .replace(/'/g, ''')
            .replace(/"/g, '"')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

/**
 * Escapes a string for use within a URL query parameter.
 * @param {string} str The string to escape.
 * @returns {string} The escaped string.
 */
function escapeUriComponent(str) {
  return encodeURIComponent(str);
}

// --- Usage Examples ---
const userInput = "<script>alert('XSS Attack!');</script>";
const userAttribute = 'john" onerror="alert(\'XSS in attribute\')';
const userUrlParam = 'search?q=<script>alert(1)</script>';

// 1. Inserting into HTML content (e.g., div.innerHTML)
const container = document.getElementById('content-area');
if (container) {
  // DANGEROUS: container.innerHTML = '<h2>User Input:</h2>' + userInput;
  container.innerHTML = '<h2>User Input (safe HTML):</h2>' + escapeHtml(userInput);
}

// 2. Inserting into an HTML attribute (e.g., input.value, a.href)
const inputElement = document.getElementById('user-name-input');
if (inputElement) {
  // DANGEROUS: inputElement.outerHTML = '<input type="text" value="' + userAttribute + '">';
  inputElement.outerHTML = '<input type="text" value="' + escapeHtmlAttribute(userAttribute) + '">';
}

// 3. Inserting into a URL query parameter
const linkElement = document.getElementById('search-link');
if (linkElement) {
  const baseUrl = '/search?param=';
  // DANGEROUS: linkElement.href = baseUrl + userUrlParam;
  linkElement.href = baseUrl + escapeUriComponent(userUrlParam);
  linkElement.textContent = "Search with encoded param";
}

// Initial HTML setup (can be in index.html)
/*
<div id="content-area"></div>
<div id="user-name-input"></div>
<a id="search-link" href="#"></a>
*/
How it works: This JavaScript snippet demonstrates how to prevent Cross-Site Scripting (XSS) vulnerabilities by implementing contextual output encoding. It provides functions to escape user-generated strings differently based on where they will be displayed: `escapeHtml` for plain HTML content, `escapeHtmlAttribute` for HTML attribute values, and `escapeUriComponent` for URL parameters. Correctly escaping content for its specific context ensures that malicious scripts are rendered harmlessly as plain text or data, rather than being executed by the browser.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs