js实现iframe
使用JavaScript创建iframe
在JavaScript中动态创建iframe可以通过document.createElement方法实现。以下是一个基本示例:
const iframe = document.createElement('iframe');
iframe.src = 'https://example.com';
iframe.width = '600';
iframe.height = '400';
document.body.appendChild(iframe);
设置iframe属性
创建后可以通过属性或setAttribute方法配置iframe:
iframe.setAttribute('allowfullscreen', '');
iframe.frameborder = '0';
iframe.id = 'customFrame';
安全限制与sandbox属性
现代浏览器要求对跨域iframe设置sandbox属性以限制权限:
iframe.sandbox = 'allow-same-origin allow-scripts';
内容写入iframe
通过contentDocument或contentWindow操作iframe内部内容(需同源):
iframe.onload = function() {
const doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc.write('<h1>Dynamic Content</h1>');
doc.close();
};
跨域通信
使用postMessage实现跨域通信:
// 父页面发送消息
iframe.contentWindow.postMessage('Hello', 'https://target-origin.com');
// iframe内接收消息
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent-origin.com') return;
console.log(event.data);
});
响应式iframe
通过CSS使iframe自适应容器大小:
iframe {
width: 100%;
height: 100%;
border: none;
}
移除iframe
从DOM中移除iframe元素:
iframe.parentNode.removeChild(iframe);






