tsfunction setHTMLWithScript() {
nextTick(() => {
if (!htmlContainerRef.value) {
return
}
const iframe = htmlContainerRef.value.querySelector('iframe')
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document
iframeDocument.open()
const styles = document.head.querySelectorAll('style')
const styleLinks = document.head.querySelectorAll('link[as="style"]')
const fontLinks = document.head.querySelectorAll('link[as="font"]')
const styleString = Array.from(styles)
.map((style) => `<style replace="true">${style.innerText}</style>`)
.join('\n')
const styleLinkString = Array.from(styleLinks)
.map((link) => link.outerHTML)
.join('\n')
const fontLinkString = Array.from(fontLinks)
.map((link) => link.outerHTML)
.join('\n')
iframeDocument.write(
genHtmlCode({
code: props.htmlCode || '',
links: `${styleLinkString}\n${fontLinkString}`,
styles: styleString,
}),
)
iframeDocument.close()
// 监听 iframe 高度变化
const originObserver = (observer = function () {
requestAnimationFrame(() => {
iframe.style.height = `${iframeDocument.body.scrollHeight}px`
if (iframeDocument.documentElement) {
iframeDocument.documentElement.className = document.documentElement.className
}
if (originObserver === observer) {
observer()
}
})
})
observer()
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43