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

已对HTML元素进行清理,为何仍触发错误弹窗?

问题解决:HTML清理后仍触发恶意弹窗的原因及修复

问题根源

你的代码逻辑存在顺序错误:先将未清理的用户输入插入临时DOM元素,再进行清理。当wrapElement.innerHTML = 用户输入时,浏览器会立即解析HTML并执行img标签的onerror事件,此时弹窗已经触发,后续的DOMPurify清理无法回溯阻止这个行为。

修复方案

调整逻辑顺序:先对用户输入的HTML字符串进行DOMPurify清理,再将清理后的内容插入DOM,避免恶意代码提前执行。

修正后的代码

JavaScript 代码

function createEle() {
  // 直接获取用户输入的字符串
  const userInput = document.getElementById("html-input").value;
  // 先清理字符串,再插入DOM
  const sanitizedHTML = DOMPurify.sanitize(userInput);
  document.getElementById("sanitized-html").innerHTML = sanitizedHTML;
}

// 若需保留showSanitizedHTML函数,改为接收字符串参数
function showSanitizedHTML(htmlString) {
  const sanitizedHTML = DOMPurify.sanitize(htmlString);
  const tempWrapElement = document.createElement('div');
  tempWrapElement.innerHTML = sanitizedHTML;
  return tempWrapElement.firstElementChild;
}

HTML 代码(无需修改)

<script src="https://cdn.jsdelivr.net/npm/dompurify@2.0.16/dist/purify.min.js"></script>
<textarea id="html-input"></textarea>
<button onclick="createEle()">Show Sanitized HTML</button>
<div id="sanitized-html"></div>

说明

修改后,用户输入的HTML字符串会先经过DOMPurify处理,移除onerror这类恶意属性,再插入到目标DOM中,从根源上阻止了恶意代码的执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:05:32