Skip to content

Commit 9f57923

Browse files
committed
feat: Support iframe rendering
1 parent b0c9662 commit 9f57923

File tree

2 files changed

+243
-228
lines changed

2 files changed

+243
-228
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
<template>
2+
<div class="iframe-wrapper">
3+
<iframe
4+
v-show="visible"
5+
ref="iframeRef"
6+
class="iframe"
7+
:srcdoc="finalSource"
8+
@load="resize"
9+
sandbox="allow-scripts allow-same-origin"
10+
/>
11+
</div>
12+
</template>
13+
14+
<script setup lang="ts">
15+
import { computed, ref, watch, nextTick } from 'vue'
16+
const resize = async () => {
17+
await nextTick()
18+
19+
const iframe = iframeRef.value
20+
if (!iframe) return
21+
22+
const doc = iframe.contentDocument
23+
if (!doc) return
24+
25+
const contentHeight = doc.documentElement.scrollHeight || doc.body.scrollHeight
26+
27+
const viewportHeight = window.innerHeight
28+
29+
const finalHeight = Math.min(contentHeight, viewportHeight)
30+
31+
iframe.style.height = finalHeight + 'px'
32+
33+
iframe.style.overflow = contentHeight > viewportHeight ? 'auto' : 'hidden'
34+
}
35+
const props = withDefaults(
36+
defineProps<{
37+
source?: string
38+
script_exec?: boolean
39+
visible?: boolean
40+
}>(),
41+
{
42+
source: '',
43+
script_exec: true,
44+
visible: true,
45+
},
46+
)
47+
48+
const iframeRef = ref<HTMLIFrameElement>()
49+
50+
// 如果不允许执行 script,就过滤掉
51+
const finalSource = computed(() => {
52+
if (props.script_exec) return props.source
53+
54+
return props.source.replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, '')
55+
})
56+
57+
// 如果 source 改变才刷新 iframe
58+
watch(
59+
() => props.source,
60+
() => {
61+
if (iframeRef.value) {
62+
iframeRef.value.srcdoc = finalSource.value
63+
}
64+
},
65+
)
66+
</script>
67+
68+
<style scoped>
69+
.iframe-wrapper {
70+
width: 100%;
71+
height: 100%;
72+
}
73+
.iframe {
74+
width: 100%;
75+
height: 100%;
76+
border: none;
77+
}
78+
</style>

0 commit comments

Comments
 (0)