跳到主要内容
uencoder

Prevent XSS (Cross-Site Scripting) attacks

XSS injects malicious scripts 为 web pages. Learn 输入 sanitization, 输出编码, 和 Content Security Policy 到 prevent XSS.

  1. 1

    XSS occurs 当用户输入是 rendered 在 HTML 无 escaping. Types: stored (persistent 在数据库), reflected (在 URL, immediate), DOM-based (客户端-边). Prevention: (1) 输出编码 — escape <, >, &, ", ' based 开上下文 (HTML, 属性, JavaScript, URL). (2) 输入 validation/sanitization. (3) Content Security Policy. (4) HttpOnly cookies. 从不插入 untrusted 数据在 dangerous locations (脚本, 事件处理程序, innerHTML).

  2. 2
    HTML 转义器 →

    转义 HTML special characters: < → &lt;, > → &gt;, & → &amp;, " → &quot;, ' → &#x27;. This prevents script injection in HTML body and attribute contexts. Use context-appropriate encoding: HTML-escape for body, attribute-escape for attributes, JavaScript-escape for script blocks, URL-encode for URLs.

  3. 3
    HTML 实体编码器 →

    编码 all characters as HTML entities for maximum safety. This is more aggressive than escaping only special characters — every character becomes &#xNN;. Use this for highly untrusted input or when you need to display code samples safely.

  4. 4

    防御在 深度: (1) 输出编码 (主防御). (2) CSP: Content-Security-Policy: default-src 'self' — blocks inline scripts. (3) HttpOnly + 安全 + SameSite cookies — prevents Cookie theft via XSS. (4) Trusted Types (Chrome) — enforces 类型-安全 DOM manipulation. (5) X-XSS-Protection: 0 (现代 browsers rely 开 CSP, 此头 能够 introduce vulnerabilities).

常见问题

什么是 差集之间 escaping 和 sanitization?
Escaping encodes 特殊 characters 所以它们是 displayed literally, 不 interpreted as markup (< → &lt;). Sanitization removes 或 neutralizes dangerous 内容 (strips <脚本> tags). Escaping 是 preferred — 它 preserves 内容 while making 它安全. Sanitization (e.g., DOMPurify) 是 needed 当你 必须允许一些 HTML (rich 文本 editors).
是 innerHTML ever 安全?
Only 具有 fully sanitized 输入. innerHTML parses 字符串 as HTML, executing 任何 <脚本> tags. Use textContent (否 HTML parsing) 为 plain 文本, 或 DOMPurify.sanitize() 为 rich 文本. 从不 use innerHTML 具有用户输入 — even escaped 输入能够是 不安全在 确定 contexts (e.g., 在属性或 事件处理程序).

解决此任务的工作流

相关工具