71 lines
2.8 KiB
HTML
71 lines
2.8 KiB
HTML
<!doctype html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="UTF-8" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||
<title>Canvas Editor Iframe Demo</title>
|
||
<style>
|
||
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial; margin: 0; padding: 16px; }
|
||
.panel { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; }
|
||
.panel input[type="text"] { width: 420px; padding: 6px 8px; font-size: 12px; }
|
||
.panel button { padding: 6px 12px; font-size: 12px; cursor: pointer; }
|
||
iframe { width: 100%; height: 80vh; border: 1px solid #e2e6ed; }
|
||
small { color: #6b7280; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<h3>父页面(同源)加载子页面 index.html(支持 ?filePath=URL)</h3>
|
||
<div class="panel">
|
||
<input id="urlInput" type="text" placeholder="输入同源文件URL或留空使用示例…" />
|
||
<input id="fileInput" type="file" accept=".json,.txt,.ocd" />
|
||
<button id="loadBtn">在 iframe 中打开</button>
|
||
<small>支持传入 JSON(完整编辑器数据)或纯文本(作为正文)。文件将以 blob: URL 形式传递,保证同源。</small>
|
||
</div>
|
||
<iframe id="editorFrame" src="./index.html" referrerpolicy="no-referrer"></iframe>
|
||
|
||
<script>
|
||
const editorFrame = document.getElementById('editorFrame')
|
||
const loadBtn = document.getElementById('loadBtn')
|
||
const urlInput = document.getElementById('urlInput')
|
||
const fileInput = document.getElementById('fileInput')
|
||
|
||
function setFrameSrc(fileUrl) {
|
||
const src = `./index.html?filePath=${encodeURIComponent(fileUrl)}`
|
||
editorFrame.src = src
|
||
console.log('[demo] 设置 iframe src:', src)
|
||
}
|
||
|
||
loadBtn.onclick = async () => {
|
||
const typedUrl = urlInput.value.trim()
|
||
if (typedUrl) {
|
||
// 直接使用同源URL
|
||
try {
|
||
// 试探一次,确保地址有效(可选)
|
||
await fetch(new URL(typedUrl, window.location.href))
|
||
setFrameSrc(typedUrl)
|
||
return
|
||
} catch (e) {
|
||
alert('无法访问该URL,请确认同源且可访问')
|
||
return
|
||
}
|
||
}
|
||
|
||
const file = fileInput.files && fileInput.files[0]
|
||
if (file) {
|
||
// 将本地选择的文件转为 blob: URL(同源),传给子页
|
||
const blobUrl = URL.createObjectURL(file)
|
||
setFrameSrc(blobUrl)
|
||
return
|
||
}
|
||
|
||
// 示例:使用内置示例JSON字符串构造 Blob
|
||
const example = {
|
||
main: [{ value: 'Hello from iframe demo' }]
|
||
}
|
||
const blob = new Blob([JSON.stringify(example)], { type: 'application/json' })
|
||
const blobUrl = URL.createObjectURL(blob)
|
||
setFrameSrc(blobUrl)
|
||
}
|
||
</script>
|
||
</body>
|
||
</html> |