You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测HTML区块中的所有JavaScript实例以保障应用安全

How to Detect All JavaScript Vectors in User-Generated HTML Blocks

Great question—XSS is a tricky threat when allowing user-generated HTML, and your current script tag check is a solid first step, but there are way more vectors attackers can use to inject malicious JS. Let's break down how to cover all the common cases with jQuery, plus some best practices:

Key JavaScript Injection Vectors to Block

Your existing check catches <script> tags, but attackers can use these workarounds to execute code:

  • Inline event handlers (e.g., onclick, onload, onmouseover)
  • javascript: protocol URLs (e.g., <a href="javascript:alert('XSS')">)
  • CSS expressions (legacy but still a risk in some environments)
  • SVG-based scripts or event handlers (SVG can embed script tags or inline events)

Full jQuery Detection Implementation

Here's a comprehensive validation function that covers all these cases, with case-insensitive checks to bypass common obfuscation tricks:

function validateCustomHtml($htmlBlock) {
    // 1. Block all <script> elements (any case, any type)
    if ($htmlBlock.find('script').length > 0) {
        throw new Error("Script tags are not allowed in custom HTML blocks");
    }

    // 2. Block inline event handlers (on* attributes, case-insensitive)
    const hasInlineEvents = $htmlBlock.find('*').filter(function() {
        for (const attr of this.attributes) {
            if (attr.name.toLowerCase().startsWith('on')) {
                return true;
            }
        }
        return false;
    }).length > 0;
    if (hasInlineEvents) {
        throw new Error("Inline event handlers (onclick, onload, etc.) are prohibited");
    }

    // 3. Block javascript: protocol URLs (case-insensitive)
    const hasJavascriptProtocol = $htmlBlock.find('a, img, iframe, area').filter(function() {
        const urlAttr = $(this).attr('href') || $(this).attr('src');
        return urlAttr && urlAttr.toLowerCase().startsWith('javascript:');
    }).length > 0;
    if (hasJavascriptProtocol) {
        throw new Error("JavaScript protocol links (javascript:) are not allowed");
    }

    // 4. Block CSS expressions (legacy but risky)
    const hasCssExpressions = $htmlBlock.find('*').filter(function() {
        const inlineStyle = $(this).attr('style');
        return inlineStyle && inlineStyle.toLowerCase().includes('expression(');
    }).length > 0;
    if (hasCssExpressions) {
        throw new Error("CSS expressions are prohibited");
    }

    // 5. Block SVG-based script vectors
    const hasSvgScript = $htmlBlock.find('svg script, svg *').filter(function() {
        if ($(this).is('script')) return true;
        // Check SVG elements for inline event handlers
        for (const attr of this.attributes) {
            if (attr.name.toLowerCase().startsWith('on')) {
                return true;
            }
        }
        return false;
    }).length > 0;
    if (hasSvgScript) {
        throw new Error("SVG-based scripts and event handlers are not allowed");
    }

    // All checks passed
    return true;
}

// Usage example with your existing jQuery object
try {
    validateCustomHtml(code); // "code" is your jQuery object
    // Proceed to save the HTML block
} catch (error) {
    alert(`Validation failed: ${error.message}`);
    // Prevent save and show user feedback
}

Critical Notes for Reliability

  • Case Insensitivity: Attackers often use mixed case (e.g., <ScRiPt>, JAVASCRIPT:alert(1)) to bypass basic checks—all the logic above handles this by converting values to lowercase.
  • Avoid Execution During Detection: When converting user HTML to a jQuery object (e.g., const code = $('<div>').html(userInput)), modern browsers won't execute script tags or inline events automatically, so this is safe.
  • Consider a Sanitization Library: For long-term security, using a dedicated library like DOMPurify is far more reliable than manual checks. It automatically strips all malicious code and handles edge cases you might miss. If you can integrate it, here's a quick example:
    const cleanHtml = DOMPurify.sanitize(userInputHtml);
    // Save cleanHtml instead of the original input
    

内容的提问来源于stack exchange,提问作者DigitalMC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:12:23