看了一些博客,进行了总结和实践
文章目录
iframe的使用
<iframe src="demo.html" height="300" width="500" name="demo" scrolling="auto" sandbox="allow-same-origin"></iframe>
- src iframe页面地址,有同域跨域之分
- name iframe命名,可通过window.frames[xxx]被调用
iframe框架中的页面与主页面之间的通信方式根据iframe中src属性是同域链接还是跨域链接,有明显不同的通信方式。
同域的api
父页面调用子页面
通过iframe的dom元素
iframe.contentWindow, 获取iframe的window对象
iframe.contentDocument, 获取iframe的document对象
var iframe = document.getElementById("iframe1");
iframe.contentWindow.document.querySelector('#div1').innerHTML='div1'
在vue中获取 iframe的window对象,dom通过ref
this.$refs.iframe.contentWindow
通过iframe的name属性
结合Name属性,通过window提供的frames获取.
window.frames[‘ifr1’]返回的就是iframe的window对象,即
window.frames['ifr1']===window
window.frames['ifr1'] == document.getElementById("iframe1").contentWindow
之后可以访问iframe的dom和方法
iframename.window.document.XX
iframename.window.function
//iframe2.window.document.getElementById(‘div1’).innerHTML=‘update’
子页面调用父页面
同理,在同域下,父页面可以获取子iframe的内容,那么子iframe同样也能操作父页面内容。在iframe中,可以通过在window上挂载的几个API进行获取.
window.parent 获取上一级的window对象,如果还是iframe则是该iframe的window对象
window.top 获取最顶级容器的window对象,即,就是你打开页面的文档
window.self 返回自身window的引用。可以理解 window===window.self
window.parent.document.XX
window.parent.function
## 跨域
### 子域不一样但主域一样
对于主域相同子域不同的两个页面,我们可以通过document.domain + iframe来解决跨域通信问题。
在两个不同子域下(某一方使用iframe嵌套在另一方),
即:http: //www.foo.com/a.html和http: //script.foo.com/b.html
两个文件中分别加上**document.domain = ‘foo.com’**,指定相同的主域,然后,两个文档就可以进行交互。
然后可以像同域一样操作iframe的内容
例子
```js
//b.html是以iframe的形式嵌套在a.html中
//www.foo.com上的a.html
document.domain = 'foo.com';
var ifr = document.createElement('iframe');//创建一个iframe元素(标签)
ifr.src = 'http://script.foo.com/b.html';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function(){
var doc = ifr.contentDocument || ifr.contentWindow.document;
// 在这里操纵b.html
alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue);
};
//script.foo.com上的b.html
document.domain = 'foo.com';
域名完全不一样
利用hash实现双方通信(已实验略麻烦)
利用 location 对象的 hash 值,通过它传递通信数据,设置 iframe的 src 后面多加个#data 字符串(data就是你要传递的数据), 监听 location.href 的变化即可获得上面的 data 信息。
例子
父页面
<template>
<div>
<button @click=