js实现frame
使用 iframe 嵌入外部页面
在 HTML 中直接使用 <iframe> 标签是最简单的方法:
<iframe src="https://example.com" width="800" height="600"></iframe>
动态创建 iframe
通过 JavaScript 动态创建 iframe 元素:

const frame = document.createElement('iframe');
frame.src = 'https://example.com';
frame.width = '800';
frame.height = '600';
document.body.appendChild(frame);
控制 iframe 内容
通过 contentWindow 和 contentDocument 访问 iframe 内部:
const iframe = document.querySelector('iframe');
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
iframeDoc.body.style.backgroundColor = 'red';
跨域通信
使用 postMessage 实现跨域通信:

// 父页面发送消息
iframe.contentWindow.postMessage('Hello', 'https://example.com');
// iframe 内接收消息
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent.com') return;
console.log(event.data);
});
替代方案:div 模拟 frame
使用 div 和 object 标签模拟 frame 效果:
<div id="frameContainer" style="width:800px; height:600px; overflow:auto;">
<object data="https://example.com" type="text/html"></object>
</div>
安全性考虑
设置 sandbox 属性限制 iframe 权限:
<iframe src="https://example.com" sandbox="allow-scripts allow-same-origin"></iframe>






