Get a Pentest and security assessment of your IT network.

Cyber Security

Preventing XSS in JavaScript Strings

TL;DR

JavaScript string manipulation can easily introduce Cross-Site Scripting (XSS) vulnerabilities if user input isn’t handled correctly. This guide shows you how to safely include data within strings, preventing attackers from injecting malicious code.

Steps to Prevent XSS in JavaScript Strings

  1. Understand the Problem: XSS happens when untrusted data (like what a user types into a form) is directly inserted into your HTML without being properly escaped. A browser will then execute this code as part of your webpage.
    • Example vulnerable code:
      let userInput = "<script>alert('XSS')</script>";
      let htmlString = "Welcome, " + userInput + "!"; // BAD!
  2. Use Text Encoding (HTML Entities): The most common and effective method is to convert potentially dangerous characters into their HTML entity equivalents. This prevents the browser from interpreting them as code.
    • For simple cases, you can use a function like this:
      function escapeHtml(unsafe) {
        return unsafe
               .replace(/&/g, "&")
               .replace(//g, ">")
               .replace("/g, """)
               .replace(/'g, "'");
      }
      
    • Example safe code:
      let userInput = "<script>alert('XSS')</script>";
      let escapedInput = escapeHtml(userInput);
      let htmlString = "Welcome, " + escapedInput + "!"; // SAFE!
  3. Use a Templating Engine: If you’re building complex UIs, use a templating engine (like Handlebars, Mustache, or React). These engines automatically escape variables by default.
    • Example using a basic template:
      // Assuming a simple template function
      template("Welcome, {{name}}!",{ name: userInput }); // SAFE!
  4. Content Security Policy (CSP): CSP is an extra layer of security that tells the browser which sources are allowed to load resources from. This can help mitigate XSS attacks even if some code gets injected.
    • Add a meta tag to your HTML:
      <meta http-equiv="Content-Security-Policy" content="default-src 'self'"">
    • This example only allows resources from the same domain. More complex policies can be defined for specific needs.
  5. Avoid innerHTML: If possible, avoid using innerHTML to insert content directly. It’s a common source of XSS vulnerabilities.
    • Instead, use methods like textContent or create DOM elements programmatically:
      let element = document.createElement('div');
      element.textContent = escapedInput; // SAFE!
  6. Sanitize User Input (with caution): While escaping is preferred, sometimes you need to allow specific HTML tags. Use a well-vetted sanitization library (like DOMPurify) to remove dangerous attributes and tags.
    • Example using DOMPurify:
      let cleanInput = DOMPurify.sanitize(userInput);
    • Important: Sanitization is complex. Incorrectly configured sanitizers can still leave vulnerabilities. Use with extreme care and keep the library updated.
  7. Regular Audits & Testing: Regularly review your code for potential XSS vulnerabilities, especially when handling user input. Consider using automated security scanners.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation