js实现frame功能
使用 iframe 实现嵌入功能
在 HTML 中直接使用 <iframe> 标签嵌入外部内容:
<iframe src="https://example.com" width="800" height="600"></iframe>
通过 JavaScript 动态创建 iframe:
const frame = document.createElement('iframe');
frame.src = 'https://example.com';
frame.width = '800';
frame.height = '600';
document.body.appendChild(frame);
使用 contentWindow 实现跨框架通信
父页面与 iframe 通信:
// 父页面获取 iframe 的 window 对象
const iframeWindow = document.getElementById('myFrame').contentWindow;
// iframe 内获取父窗口
const parentWindow = window.parent;
使用 postMessage 安全通信
父页面发送消息:
const iframe = document.getElementById('myFrame');
iframe.contentWindow.postMessage('Hello from parent', 'https://example.com');
iframe 接收消息:
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent-site.com') return;
console.log('Received message:', event.data);
});
使用 sandbox 属性增强安全性
限制 iframe 的权限:
<iframe src="https://example.com" sandbox="allow-scripts allow-same-origin"></iframe>
常用 sandbox 值组合:
allow-scripts: 允许执行脚本allow-same-origin: 允许同源访问allow-forms: 允许提交表单allow-popups: 允许弹出窗口
动态修改 iframe 内容
通过 srcdoc 属性直接设置内容:
const frame = document.getElementById('myFrame');
frame.srcdoc = '<html><body><h1>Dynamic Content</h1></body></html>';
通过 contentDocument 修改已加载的 iframe:
const frame = document.getElementById('myFrame');
const frameDoc = frame.contentDocument || frame.contentWindow.document;
frameDoc.body.innerHTML = '<h1>Modified Content</h1>';
处理跨域限制
同源策略下的解决方案:
- 使用 postMessage 进行安全通信
- 设置正确的 CORS 头部
- 使用代理服务器中转请求
- 考虑使用 window.name 传输技术(已过时)
检测 iframe 加载状态
监听 load 事件:
document.getElementById('myFrame').addEventListener('load', () => {
console.log('Frame finished loading');
});
检测加载错误:

document.getElementById('myFrame').addEventListener('error', () => {
console.error('Frame failed to load');
});






