javascript - 将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 中。有没有办法防止这种情况?
解决方案
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);
}
});
}
推荐阅读
- html - 无法从网站冗余下拉列表中选择或更新
- android - 没有找到改造的面临
- arrays - 如何从 Python 3 中的 CLI 输出的特定列和行中获取值
- javascript - Chrome 上的 Anychart 下载中断
- mysql - 如何在 Django 中选择同一字段的两个范围?
- javascript - 试图用 sinon 编写我的第一个 mocha 单元测试,但无法正确地建立心智模型
- sql - 如何从 SQL 语法中创建 PG 函数和触发器?
- css - SassError:@extend 类失败:tailwind vue 无法将多个 tailwind 类合并到一个自定义类中
- excel - 在 VBA 中调试 Excel 类库加载项,在 Visual Studio VB .Net 中创建和运行
- python - 创建和删除文件时出现权限错误