iframe中父子窗口的调用

来源:互联网 发布:网络商标到期 编辑:程序博客网 时间:2024/05/15 12:24

一、iframe标签详解

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

(1)操作子窗口:frames[‘child’].contentDocument || frames[‘child’].document

1.首先获取iframe节点:

 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;

其他浏览器:

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

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

注意:iframe元素遵守同源政策,只有当父页面与框架页面来自同一个域名,两者之间才可以用脚本通信,否则只有使用window.postMessage方法。

(2)操作父窗口:iframe.parent
iframe窗口内部,使用window.parent引用父窗口。如果当前页面没有父窗口,则window.parent属性返回自身。因此,可以通过window.parent是否等于window.self,判断当前窗口是否为iframe窗口。

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

二、iframe中父子窗口操作实例

父页面:

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

子页面:

<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;}
0 0