feat: add dangerouslySetInnerHTML attr

This adds are new attribute to Elements, "dangerouslySetInnerHTML", which like the same attribute from React allows one to take a stirng of unescaped HTML and render it unconditionally. This is of course a potentially dangerous operation that can open your app up to XSS attacks, but for interoperating with existing content management systems and libraries that output HTML (e.g. markdown renderers).

Using "dangerouslySetInnerHTML" on an element with children will generate an error within createElement, since it doesn't make sense to have both children and inner HTML.
This commit is contained in:
M. George Hansen 2021-01-02 21:24:17 -08:00
parent 7f9743a21f
commit eef25d360d
4 changed files with 61 additions and 3 deletions

View file

@ -34,8 +34,12 @@ const renderElement = (elem: Element): string => {
let output = "";
output += startTag(elem);
for (const child of elem.children) {
output += renderElement(child);
if (elem.attributes.dangerouslySetInnerHTML != null) {
output += elem.attributes.dangerouslySetInnerHTML;
} else {
for (const child of elem.children) {
output += renderElement(child);
}
}
output += endTag(elem);
return output;
@ -55,6 +59,11 @@ const startTag = (elem: HTMLElement): string => {
continue;
}
// Ignore the special attr for setting raw inner HTML.
if (attrName === "dangerouslySetInnerHTML") {
continue;
}
let normalizedAttrName = escapeHtml(attrName.toLowerCase());
if (normalizedAttrName === "classname") {
normalizedAttrName = "class";