嵌入式内容
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-scripts和allow-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 object:embed 自闭合无回退内容,object 可包含回退内容。
3. 安全最佳实践
<iframe
src="https://trusted-site.com/widget"
sandbox="allow-scripts allow-forms"
allow="geolocation"
referrerpolicy="no-referrer"
loading="lazy"
title="第三方小组件"
>
</iframe>