学习:https://www.jianshu.com/p/7ec986aa28a7
<iframe src="demo.html" height="300" width="500" name="demo" scrolling="auto" sandbox="allow-same-origin"></iframe>
1、基本属性
- src iframe页面地址,有同域跨域之分
- height iframe高度
- width iframe宽度
- name iframe命名,可通过window.frames[xxx]被调用
- scrolling iframe滚动模式
sandbox html5新特性,用于限制iframe的功能
2、调用
let iframe = document.getElementById('demo'); let iwindow = iframe.contentWindow; // 获取iframe的window对象 let idoc = iframe.contentDocument; // 获取iframe的document对象 let iframe = window.frames['demo']3、iframe跨域
1、document.domain + iframe
网页a(http://www.easonwong.com)和网页b(http://script.easonwong.com),两者都设置document.domain = ‘easonwong.com’(这样浏览器就会认为它们处于同一个域下),然后网页a再创建iframe上网页b,就可以进行通信啦~!
网页adocument.domain = 'easonwong.com'; var ifr = document.createElement('iframe'); ifr.src = 'http://script.easonwong.com'; ifr.style.display = 'none'; document.body.appendChild(ifr); ifr.onload = function(){ let doc = ifr.contentDocument || ifr.contentWindow.document; // 在这里操纵b.html };网页b
document.domain = 'easonwong.com';2、iframe跨域通讯之postMessage
postMessage是html5的新特性,使用postMessage进行数据传递,通过Message监听通信事件。
网页adocument.domain = 'easonwong.com'; var ifr = document.createElement('iframe'); ifr.src = 'http://script.easonwong.com'; ifr.style.display = 'none'; document.body.appendChild(ifr); // 发送数据 ifr.postmessage('hello, I`m a', 'http://script.easonwong.com');网页b
// 监听message事件 window.addEventListener('message', receiver, false); function receiver(e) { if (e.origin == 'http://www.easonwong.com') { if (e.data == 'hello, I`m a') { e.source.postMessage('hello, I`m b', e.origin);信息 } } }4、iframe的其他用途
用iframe进行异步请求
在很久很久很久以前,久到ajax还没出现的时候,人们会用iframe来进行异步请求。大概就是异步创建iframe,然后后台返回数据在iframe中,我们在从里面获取数据。
例如在我做过的一个项目中,通过iframe.src传入一个文件下载地址,实现无需打开新窗口下载文件。
- 引用/展示第三方内容
- 需要独立样式和带有交互的内容,例如幻灯片
- sandbox沙箱隔离
- 历史记录管理
5、iframe的安全问题
1、iframe小广告
2、防嵌套页面操作
在前端领域,我们可以通过window.top来防止我们页面被嵌套。
if(window != window.top){ window.top.location.href = myURL; }
或者通过window.location.host来检测是否跨域了
if (top.location.host != window.location.host) { top.location.href = window.location.href; }
而后端也可以做对应的防范措施,通过设置X-Frame-Options响应头来确保自己网站的内容没有被嵌到别人的网站中去,也从而避免了点击劫持 (clickjacking) 的攻击。6、缺点
1、阻塞主页面的onload
2、搜索引擎无法解读该页面,不利于seo
3、iframe与主页面共享连接池,浏览器对相同区域有限制会受影响
