js实现frame功能
使用iframe嵌入外部页面
在HTML中直接使用<iframe>标签嵌入外部页面是最简单的方法。通过设置src属性指定目标URL,width和height控制尺寸。
<iframe
src="https://example.com"
width="800"
height="600"
title="Embedded Page">
</iframe>
动态创建iframe元素
通过JavaScript动态创建iframe并插入DOM,适用于需要条件加载的场景。使用document.createElement生成元素后设置属性。
const iframe = document.createElement('iframe');
iframe.src = 'https://example.com';
iframe.style.width = '100%';
iframe.style.height = '400px';
document.body.appendChild(iframe);
跨域通信解决方案
当主页面与iframe内容跨域时,使用postMessage实现安全通信。主页面发送消息,iframe通过监听message事件接收。
// 主页面发送消息
const iframe = document.querySelector('iframe');
iframe.contentWindow.postMessage('Hello', 'https://target-origin.com');
// iframe内接收消息
window.addEventListener('message', (event) => {
if (event.origin !== 'https://trusted-origin.com') return;
console.log('Received:', event.data);
});
响应式iframe尺寸调整
通过监听窗口变化事件动态调整iframe尺寸。使用resize事件结合requestAnimationFrame优化性能。
function resizeIframe() {
const iframe = document.getElementById('responsive-iframe');
iframe.style.height = `${window.innerHeight * 0.8}px`;
}
window.addEventListener('resize', () => {
window.requestAnimationFrame(resizeIframe);
});
内容安全策略配置
对于需要严格安全控制的场景,通过<iframe>的sandbox属性限制权限。可配置值包括allow-scripts、allow-same-origin等。
<iframe
src="https://example.com"
sandbox="allow-scripts allow-forms"
width="600"
height="400">
</iframe>






