JavaScript Interview Question #138

What is cross-site scripting (XSS)?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

XSS is a web security vulnerability in which attacker-controlled content is executed as script in another user's browser under the application's origin. It can arise when untrusted data is inserted into HTML, JavaScript, URLs, or other executable contexts without appropriate output handling.

Detailed Explanation

XSS is a web security vulnerability in which attacker-controlled content is executed as script in another user's browser under the application's origin. It can arise when untrusted data is inserted into HTML, JavaScript, URLs, or other executable contexts without appropriate output handling.

A major defense is context-appropriate encoding and avoiding unsafe HTML injection. Prefer textContent for plain text, use trusted framework templating correctly, validate dangerous URL schemes, and apply a well-designed Content Security Policy as an additional defense.

Code Example

const message = document.querySelector("#message");
const userInput = "<img src=x onerror=alert(1)>";

// Safe for plain text:
message.textContent = userInput;

// Avoid assigning untrusted content directly to innerHTML.