前置知识: HTML5

嵌入式内容

00:00
1 min Intermediate 2026/6/14

iframe、embed、object

1. iframe 元素

<iframe src="https://example.com" width="800" height="600" title="嵌入页面"></iframe>

1.1 sandbox 安全沙箱

<iframe src="untrusted.html" sandbox></iframe>
<iframe src="widget.html" sandbox="allow-scripts allow-forms allow-same-origin"></iframe>
sandbox 允许的功能
(空)禁止所有
allow-scripts执行脚本
allow-same-origin请求
allow-forms提交

安全警告:同时使用 allow-scriptsallow-same-origin 可能导致沙箱被绕过。

1.2 iframe 通信

// 父页面 → iframe
iframe.contentWindow.postMessage({ type: 'DATA' }, 'https://example.com');

// 接收消息
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://example.com') return;
  console.log(event.data);
});

1.3 srcdoc 内联内容

<iframe srcdoc="<h1>内联内容</h1>" sandbox="allow-scripts"></iframe>

2. embed 与 object

<embed src="document.pdf" type="application/pdf" width="800" height="600" />

<object data="document.pdf" type="application/pdf" width="800" height="600">
  <p>您的浏览器不支持 PDF 预览</p>
</object>

embed vs objectembed闭合回退内容object回退内容

3. 安全最佳实践

<iframe
  src="https://trusted-site.com/widget"
  sandbox="allow-scripts allow-forms"
  allow="geolocation"
  referrerpolicy="no-referrer"
  loading="lazy"
  title="第三方小组件"
>
</iframe>

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式