首页 > 解决方案 > 将html代码替换为文本后,文本转换为html并被执行,如何防止呢?

问题描述

在页面上您可以创建新博客,在编辑器中您可以插入例如

<p>MyWord <img src=x onerror=alert(something)></p>

如果您发布它,您将在博客页面上看到整个字符串作为文本。但是,如果我现在将“MyWord”替换为其他内容,则会执行 html 字符串。替换我使用的词

function replaceWords(words) {
  const container = $('body :not(script):not(.myClass)');

  for (const key of Object.keys(words)) {
    container
      .contents()
      .filter((_, i) => {
        if (i.nodeType === 3 && i.nodeValue.match(words[key].reg)) {
          return i.nodeType === 3 && i.nodeValue.match(words[key].reg);
        }
      })
      .replaceWith(function () {
        return this.nodeValue.replace(words[key].reg, createWordTag(words[key]));
      });
  }
}

所以我怀疑编辑器阻止了 html 字符串的执行,但是在我替换了这个词之后,该字符串作为 html 代码插入回 DOM 中。有没有办法防止这种情况?

标签: javascripthtmljquerydomxss

解决方案


jQuery 的.replaceWith()方法将替换内容视为要呈现的 HTML(如果它是字符串),而不是纯文本。

而不是替换元素,只需分配给文本节点的nodeValue.

如果您只循环一次 DOM 元素,然后在其中执行所有文本替换,那也会更好。

function replaceStr(myStrArr) {
  const container = $('body :not(script)');
  container
    .contents()
    .each((_, el) => {
      if (el.nodeType == 3) {
        el.nodeValue = myStrArr.reduce(({
          reg,
          newStr
        }, text) => text.replace(reg, newStr), el.nodeValue);
      }
    });
}

推荐阅读