From 9103ae2f668faafec85eb710b6db876906014c35 Mon Sep 17 00:00:00 2001 From: Jun Date: Thu, 24 Feb 2022 15:51:22 -0800 Subject: [PATCH] Create serialize-doctype.ts --- src/dom/serialize-doctype.ts | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/dom/serialize-doctype.ts diff --git a/src/dom/serialize-doctype.ts b/src/dom/serialize-doctype.ts new file mode 100644 index 0000000..b49899e --- /dev/null +++ b/src/dom/serialize-doctype.ts @@ -0,0 +1,49 @@ +/// + +const htmlEscape = (str: string | null): string => { + if (!str) + return ''; + + const escaped = []; + str.split('').forEach(char => { + if (char == '&') { + char = '&'; + } else if (char == '\'') { + char = '''; + } else if (char == '"') { + char = '"'; + } else if (char == '<') { + char = '<'; + } else if (char == '>') { + char = '>'; + } + escaped.push(char); + }); + + return escaped.join(''); +} + +const docRule: TrustedTypePolicyOptions = { + createHTML: (ignored: string, doctype?: DocumentType | null): string => { + if (!doctype) + return ''; + + const name = htmlEscape(doctype.name); + const internalSubset = htmlEscape(doctype.internalSubset); + const publicId = `"${htmlEscape(doctype.publicId)}"`; + const systemId = `"${htmlEscape(doctype.systemId)}"`; + + return ``; + } +} + +let doctypePolicy: TrustedTypePolicy | TrustedTypePolicyOptions; +if ((window as any).trustedTypes) { + doctypePolicy = (window as any).trustedTypes.createPolicy('html2canvas', docRule); +} else { + doctypePolicy = docRule; +} + +export const serializeDoctype = (doctype?: DocumentType | null): string => { + doctypePolicy.createHTML('', doctype); +}