javascript - How to display escaped HTML inside a code tag generated from markdown sanitized source?
问题描述
I'm developing an app that collects feedbacks from customers. The input interface enables them to use markdown for more organized inputs. I'm implementing a preview feature that parses the markdown to HTML and displays it in a div.
I'm using the DOMPurify package to sanitize the user input before parsing the markdown with the Marked JS library. We are only allowing markdown, so HTML inputs are by default escaped. The exception is that the users can include code snippets in their feedbacks; they can use the code example syntax from markdown.
We are escaping every HTML tag that is entered before parsing, because when the markdown is parsed then the escaped HTML parts are not showing properly inside the <code>
tag.
How can I manage to display escaped HTML inside the <code>
tag? Is there a better way to block this kind of XSS?
JS code that is generating and displaying the parsed markdown input:
function showMarkdownPreview(sourceHtmlComponentId, targetHtmlComponentId) {
let sourceElement = document.getElementById(sourceHtmlComponentId);
let targetElement = document.getElementById(targetHtmlComponentId);
let san = sanitizeHTML(sourceElement.value);
targetElement.innerHTML = DOMPurify.sanitize(marked(san), { USE_PROFILES: { html: true } });
}
var sanitizeHTML = function (str) {
let regex = /[&|<|>|"|']/g;
let htmlString = str.replace(regex, function (match) {
if (match === "&") {
return "&";
} else if (match === "<") {
return "<"
} else if (match === ">") {
return ">";
} else if (match === '"') {
return """;
} else {
return "'";
}
});
return htmlString;
};
This is what the affected part looks like of the parsed HTML:
<pre>
<code>&lt;p&gt;dfsfsdfsdf&lt;/p&gt;</code>
</pre>
The example input of the parser:
Output of the parser:
解决方案
推荐阅读
- android - 带有回收站视图的搜索视图在片段中不起作用
- reactjs - 带有 useRef 的多个 div
- c# - 从未引用的程序集中将用户机密加载到配置中的合理方法?
- python - 如何解释模型预测结果?
- javascript - 简单的条件 IF 不能正常工作(属性未定义错误)
- swift - 为什么 swift Combine 中的 .collect() 运算符总是发送 .unlimited 需求,而不管上游发布者的需求如何?
- python - 我可以将恢复行为作为插件添加到 ROS FlexBE 吗?
- json - 如何在 Apache Beam 中解析 2 个 json 文件
- sql - 用计数更新表
- flutter - 如何将渐变色应用到网页上的 Flutter Icon?