js实现frame
使用JavaScript创建iframe元素
在JavaScript中动态创建iframe可以通过document.createElement方法实现。以下是基本实现方式:
const iframe = document.createElement('iframe');
iframe.src = 'https://example.com';
iframe.width = '500px';
iframe.height = '300px';
document.body.appendChild(iframe);
设置iframe属性
创建后可以设置各种属性来控制iframe的行为和外观:
iframe.setAttribute('allowfullscreen', '');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('scrolling', 'auto');
安全限制与沙箱
现代浏览器对iframe有严格的安全限制,可以通过sandbox属性增强安全性:

iframe.sandbox = 'allow-same-origin allow-scripts allow-forms';
跨域通信
如果需要与iframe内容通信,可以使用postMessage API:
// 父窗口发送消息
iframe.contentWindow.postMessage('Hello', 'https://example.com');
// iframe内接收消息
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent.com') return;
console.log(event.data);
});
检测iframe加载
监听iframe的load事件可以知道内容何时加载完成:

iframe.addEventListener('load', () => {
console.log('iframe加载完成');
});
响应式iframe
要使iframe适应不同屏幕尺寸,可以添加CSS:
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.border = 'none';
移除iframe
当不再需要iframe时,可以从DOM中移除:
iframe.parentNode.removeChild(iframe);
动态内容写入
可以直接向iframe写入HTML内容而不需要外部URL:
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc.write('<html><body><h1>动态内容</h1></body></html>');
doc.close();






