不使用innerHTML搭配replace方法的安全替代方案有哪些?
无innerHTML安全实现方案
你可以通过操作原生DOM节点的方式实现完全一致的效果,全程规避XSS注入风险,实现代码如下:
function identifier(reg, className) { const regex = new RegExp(reg, "gi"); const pList = document.querySelectorAll("p"); pList.forEach(p => { // 初始p仅含纯文本,直接读取文本内容 const rawText = p.textContent; // 清空原有内容 p.textContent = ''; let lastMatchedIndex = 0; let matchResult; // 遍历所有匹配的标识符 while ((matchResult = regex.exec(rawText)) !== null) { // 插入匹配项之前的普通文本 if (matchResult.index > lastMatchedIndex) { p.appendChild(document.createTextNode(rawText.slice(lastMatchedIndex, matchResult.index))); } // 创建带指定类名的span包裹匹配内容 const styleSpan = document.createElement('span'); styleSpan.className = className; styleSpan.textContent = matchResult[0]; p.appendChild(styleSpan); lastMatchedIndex = regex.lastIndex; } // 插入末尾未匹配的剩余文本 if (lastMatchedIndex < rawText.length) { p.appendChild(document.createTextNode(rawText.slice(lastMatchedIndex))); } }); } identifier("[^<>]+?:", "identifier");
方案优势
- 全程使用
textContent、createElement等原生DOM API,完全规避innerHTML带来的XSS注入风险,即使文本内容包含恶意代码也不会被执行 - 匹配逻辑和最终渲染效果与你的原有代码完全一致
- 适配你当前p标签仅含纯文本的场景,代码复杂度和原有实现基本持平
内容的提问来源于stack exchange,提问作者Anon
相关产品推荐
相关产品推荐

