iframe中父子窗口的调用

1、iframe标签详解

<iframe src="1.html" frameborder="0" id="child"></iframe>

(1)操做子窗口:frames['child'].contentDocument || frames['child'].document

1.首先获取iframe节点:html

var myIframe = document.getElementById('child');
或
var myIframe = frames['child']; 
或
var myIframe = window.frames['child'];
或
var myIframe = child;

window对象的frames属性返回一个相似数组的对象,成员是全部子窗口的window对象。好比,frames[0]返回第一个子窗口。若是iframe设置了idname,那么属性值会自动成为全局变量,而且能够经过window.frames属性引用,返回子窗口的window对象数组

window.frames['child'] === frames['child'] === child === document.getElementById('child');

2.而后获取iframe包含的document对象:浏览器

IE浏览器:框架

var childDocument = myIframe.document;

其余浏览器:post

var childDocument = myIframe.contentWindow.document;    
或
var childDocument = myIframe.contentDocument;

contentWindow属性得到iframe节点包含的window对象,
contentDocument属性得到包含的document对象,等价于contentWindow.documentthis

注意:iframe元素遵照同源政策,只有当父页面与框架页面来自同一个域名,二者之间才能够用脚本通讯,不然只有使用window.postMessage方法。code

(2)操做父窗口:iframe.parent

iframe窗口内部,使用window.parent引用父窗口。若是当前页面没有父窗口,则window.parent属性返回自身。所以,能够经过window.parent是否等于window.self,判断当前窗口是否为iframe窗口。htm

if (window.parent !== window.self) {
    //当前窗口是子窗口
    var parentDocument = window.parent.document;
}

2、iframe中父子窗口操做实例

父页面:对象

<body>
<div id="myList">
</div>
<iframe src="1.html" frameborder="0" id="child"></iframe>
</body>

子页面:get

<body>
<div id="content">
这是子页面
</div>
</body>

父页面调取子页面内容:

frames['child'].onload = function () {
    var childDocument = this.contentDocument || this.document;   
}

子页面调取父页面内容:

if (window.parent !== window.self) {
    var parentDocument = window.parent.document;
}