js实现iframe
使用 JavaScript 动态创建 iframe
在 JavaScript 中动态创建 iframe 可以通过 document.createElement 方法实现。以下是一个完整的示例:
// 创建 iframe 元素
const iframe = document.createElement('iframe');
// 设置 iframe 属性
iframe.src = 'https://example.com';
iframe.width = '600';
iframe.height = '400';
iframe.frameBorder = '0'; // 移除边框
iframe.allowFullscreen = true;
// 将 iframe 添加到 DOM 中
document.body.appendChild(iframe);
通过 innerHTML 插入 iframe
另一种方法是使用 innerHTML 直接插入 HTML 字符串:
document.body.innerHTML += `
<iframe
src="https://example.com"
width="600"
height="400"
frameborder="0"
allowfullscreen>
</iframe>
`;
控制 iframe 的内容
可以通过 contentWindow 或 contentDocument 访问 iframe 的内部文档对象:
const iframe = document.querySelector('iframe');
// 等待 iframe 加载完成
iframe.onload = function() {
// 访问 iframe 的 document 对象
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// 修改 iframe 内部内容
iframeDoc.body.style.backgroundColor = 'lightblue';
// 在 iframe 中执行脚本
iframe.contentWindow.alert('Hello from parent window!');
};
跨域 iframe 的安全限制
需要注意浏览器的同源策略限制:
- 只有当 iframe 与父页面同源时,才能完全访问其内容
- 跨域 iframe 只能进行有限交互,如监听其加载事件
- 可以通过
postMessage实现安全的跨域通信
响应式 iframe
要使 iframe 适应不同屏幕尺寸,可以使用 CSS:
iframe {
width: 100%;
height: 100%;
max-width: 800px;
border: none;
}
移除 iframe
当不再需要 iframe 时,可以从 DOM 中移除:

const iframe = document.querySelector('iframe');
iframe.parentNode.removeChild(iframe);






