Files
BetterSEQTA-Plus/src/seqta/utils/stringToHTML.ts
T
AdenMGB 8a5424c5a4 fix: harden extension security and plugin reliability
Address audit findings across background handlers, openers,
plugins, and UI: URL allowlists, XSS reductions, popup lifecycle
fixes, plugin dispose/cleanup, cloud sync hardening, global search
mathjs sandbox, and settings storage fixes.
2026-06-17 10:52:43 +09:30

32 lines
1.1 KiB
TypeScript

import DOMPurify from "dompurify";
/**
* Converts an HTML string into a DOM element, with sanitization and optional styling.
*
* This function first sanitizes the input HTML string using DOMPurify to prevent XSS attacks.
* The sanitization process allows only safe URI schemes in links and media.
* Then, it parses the sanitized string into an HTML document and returns its body.
* Optionally, it can apply predefined CSS styles to the body element.
*
* @param {string} str The HTML string to convert.
* @param {boolean} [styles=false] Whether to apply predefined styles to the document body.
* @returns {HTMLElement} The body element of the parsed and sanitized HTML document.
*/
export default function stringToHTML(str: string, styles = false) {
const parser = new DOMParser();
str = DOMPurify.sanitize(str, {
ALLOWED_URI_REGEXP:
/^(?:(?:https?|mailto|tel):|\/|#|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
});
const doc = parser.parseFromString(str, "text/html");
if (styles) {
doc.body.style.cssText =
"height: auto; overflow: scroll; margin: 0px; background: var(--background-primary);";
}
return doc.body;
}