Commit 5b7c549b authored by nick zheng's avatar nick zheng

chore: 排除mermaid渲染的svg标签净化

parent 838771d1
...@@ -17,6 +17,7 @@ const katexOptions: MarkedKatexOptions = { ...@@ -17,6 +17,7 @@ const katexOptions: MarkedKatexOptions = {
output: 'html', output: 'html',
} }
// Mermaid初始化
mermaid.initialize({ mermaid.initialize({
startOnLoad: false, startOnLoad: false,
htmlLabels: true, htmlLabels: true,
...@@ -167,12 +168,40 @@ export function createMarkedInst() { ...@@ -167,12 +168,40 @@ export function createMarkedInst() {
}, },
postprocess(html: string) { postprocess(html: string) {
initMermaidPanzoom() initMermaidPanzoom()
return DOMPurify.sanitize(html) return getSanitizedHtml(html)
}, },
}, },
}) })
} }
// 获取净化HTML, 排除Mermaid render的svg标签
function getSanitizedHtml(html: string) {
const mermaidElementRegex = /<div class="mermaid-viewer"><svg(.*?)>(.*?)<\/svg><\/div>/gs
const mermaidObjects: { placeholder: string; content: string }[] = []
let processedHtml = html
let match: RegExpExecArray | null = null
let i = 0
while ((match = mermaidElementRegex.exec(html)) !== null) {
const fullMatch = match[0]
const placeholder = `MERMAID_PLACEHOLDER_${i}`
mermaidObjects.push({ placeholder, content: fullMatch })
processedHtml = processedHtml.replace(fullMatch, placeholder)
i++
}
const sanitizedHtmlWithoutMermaid = DOMPurify.sanitize(processedHtml)
let sanitizedHtml = sanitizedHtmlWithoutMermaid
for (const mermaidItem of mermaidObjects) {
sanitizedHtml = sanitizedHtml.replace(mermaidItem.placeholder, mermaidItem.content)
}
return sanitizedHtml
}
export function markdownParser(markdown: string) { export function markdownParser(markdown: string) {
return createMarkedInst().parse(markdown) return createMarkedInst().parse(markdown)
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment