Iframe详解html
<iframe src="demo.html" height="300" width="500" name="demo" scrolling="auto" sandbox="allow-same-origin"></iframe>
iframe的一些基本属性:前端
咱们能够经过contentWindow
和contentDocument
两个API获取iframe的window对象和document对象。html5
let iframe = document.getElementById('demo'); let iwindow = iframe.contentWindow; // 获取iframe的window对象 let idoc = iframe.contentDocument; // 获取iframe的document对象
刚刚咱们提到了iframe的name属性,咱们也能够经过window.frames[iframeName]来调用iframe ajax
let iframe = window.frames['demo']
window.self
,
window.parent
,
window.top
这三个属性分别获取自身window对象,父级window对象,顶级window对象。
iframe1.self === iframe1 iframe1.parent === iframe2 iframe2.parent === window iframe1.top === window
什么是同域什么跨域咧?同域跨域的区别在哪咧?咱们通常会使用iframe来进行父子页面的通讯,然鹅父子页面是否同域决定了它们之间可否进行通讯。后端
js遵循同源策略,即同协议,同域名,同端口号,不然都算跨域。跨域
对于主域相同子域不一样的两个页面,咱们能够经过document.domain + iframe来解决跨域通讯问题。浏览器
document.domain = 'easonwong.com'
(这样浏览器就会认为它们处于同一个域下),而后网页a再建立iframe上网页b,就能够进行通讯啦~
document.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';
postMessage是html5的新特性app
postMessage介绍框架
兼容性 IE8以上
咱们能够经过html5这个新特性进行iframe间的跨域通讯,使用postMessage进行数据传递,经过Message监听通讯事件。
网页a
document.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);信息 } } }
在移动端Hybrid混合模式中常常用到JSBridge进行JS和Native之间的通讯,其中咱们能够经过iframe的方式实现JS调用Native的方法。
以上提到的方法就是URL SCHEME拦截
在好久好久好久之前,久到ajax还没出现的时候,人们会用iframe来进行异步请求。大概就是异步建立iframe,而后后台返回数据在iframe中,咱们在从里面获取数据。
例如在我作过的一个项目中,经过iframe.src传入一个文件下载地址,实现无需打开新窗口下载文件。
引用/展现第三方内容
须要独立样式和带有交互的内容,例如幻灯片
sandbox沙箱隔离
历史记录管理
在前端领域,咱们能够经过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) 的攻击。
内容安全策略(CSP)用于检测和减轻用于 Web 站点的特定类型的攻击,例如 XSS 和数据注入等。
经过CSP配置sandbox和child-src能够设置iframe的有效地址,它限制适iframe的行为,包括阻止弹出窗口,防止插件和脚本的执行,并且能够执行一个同源策略。
咱们能够在html头部中加上<meta>
标签
<meta http-equiv="Content-Security-Policy" content="child-src 'unsafe-inline' 'unsafe-eval' www.easonwong.com">
或者经过HTTP头部信息加上Content-Security-Policy字段