全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-17 7 分钟 ✍️ juanwangdev

HTML iframe与嵌入内容

iframe用于在页面中嵌入外部内容,是组件化嵌入的核心方式。

iframe基本用法

标准语法

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

必要属性

属性说明必填
src嵌入页面URL
title无障碍描述
width宽度
height高度

安全属性配置

sandbox沙箱

限制iframe权限,提升安全性。

HTML
<iframe src="https://example.com" sandbox></iframe>
sandbox值允许的操作
无值最低权限,仅显示内容
allow-scripts允许执行脚本
allow-forms允许表单提交
allow-same-origin允许同源访问
allow-popups允许弹出窗口
allow-top-navigation允许跳转顶级页面

生产环境建议使用sandbox最小权限原则。

allow权限策略

HTML
<iframe
  src="https://example.com"
  allow="camera; microphone; geolocation">
</iframe>

srcdoc内联内容

HTML
<iframe srcdoc="<h1>内联HTML内容</h1><p>无需额外请求</p>">
</iframe>

懒加载

HTML
<iframe src="https://example.com" loading="lazy"></iframe>

loading="lazy"延迟加载视口外的iframe,优化页面性能。

跨域通信

postMessage发送消息

JavaScript
// 父页面发送
const iframe = document.querySelector('iframe');
iframe.contentWindow.postMessage(
  { type: 'greeting', data: 'Hello' },
  'https://example.com'
);

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

iframe向父页面发送

JavaScript
// iframe内发送
window.parent.postMessage(
  { type: 'response', data: 'World' },
  'https://parent.com'
);

// 父页面接收
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://example.com') return;
  console.log('收到响应:', event.data);
});

验证event.origin防止恶意消息攻击。

响应式iframe

保持宽高比

HTML
<style>
  .iframe-container {
    position: relative;
    width: 100%;
    padding-bottom: 56.25%; /* 16:9 */
  }
  .iframe-container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>

<div class="iframe-container">
  <iframe src="https://example.com"></iframe>
</div>

其他嵌入方式

embed标签

HTML
<embed src="file.pdf" type="application/pdf" width="600" height="400">

object标签

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

嵌入方式对比

方式适用场景特点
iframe网页嵌入独立文档上下文
embed插件内容需要插件支持
object多媒体/文档提供fallback内容

要点总结

  • iframe必须有src和title属性
  • sandbox限制权限提升安全性
  • loading="lazy"优化性能
  • postMessage实现跨域安全通信
  • 始终验证消息来源origin
  • 响应式布局保持宽高比

📝 发现内容有误?点击此处直接编辑

← 上一篇 HTML SVG与矢量图形
下一篇 → HTML响应式多媒体与自适应
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库