html之iframe

在A.html页面中签了iframe标签,iframe的src指向B.html,如果这时候想在A.html页面中通过脚本获取B.html中的某个元素.

A.html:

<html>
...
<iframe src='B.html'>
</iframe>
</html>

B.html:

<html>
...
<div id='testDiv'>
test...
</div>
</html>

这时候可通过

//先在A页面获取iframe对象
var A_iframe=document.getElementsByTagName('iframe');
//再通过该对象的contentWindow属性,获取B页面中的window对象
var B_window=A_iframe[0].contentWindow;
//再通过window对象调用document等方法
var testDiv=B_window.document.getElementById('testDiv');

这个是可以获取到B页面的DOM对象的。

但是!!如果两个页面存在跨域问题,则会报错:SecurityError: Blocked a frame with origin "******" from accessing a cross-origin frame.

所以,不管是ajax,还是iframe都会存在跨域的问题。。。

因此,只能把A.html和B.html两个页面都放到同一个域下,就不会报错,也可以在A页面获取B页面的内容

---http://127.0.0.1/html5/A.html (B.html也是在hmtl5文件夹下)

//=========================20150127 start=====================================//

从嵌套子页面,如B页面,找到A页面中嵌套的其他iframe,如C页面,则在B页面中,可通过如下代码获取到A页面的对象:

//在B页面,通过window.top可获得其父页面,也就是A页面的window对象

var A_window_obj=window.top;

//然后通过A页面的window对象,以及在A页面中定义的iframe的name属性来获取对应的iframe窗口对象

var C_iframe_window_obj=A_window_obj.frames["C_content"];

//此时,C_iframe_window_obj就是iframe为C的页面的window对象了。

//也就是,只要A,B,C三者同一域,它们是互通的。

<html>
...
<iframe src='B.html' name='B_content'>
</iframe>
<iframe src='C.html' name='C_content'>
</iframe>
</html>

  

小结:

从上到下访问的方式:

document.getElementsByTagName('iframe')[0].contentWindow

从下到上访问的方式(通过iframe的name属性):

window.top--获取父页面的window

window.top.frames["C_content"]--获取父页面中其他嵌套的iframe页面的window

//=========================20150127 end=====================================//

 可参考:

iframe与主框架跨域相互访问方法-->>http://blog.csdn.net/fdipzone/article/details/17619673

contentWindow-->>http://www.cnblogs.com/wkylin/archive/2011/09/26/2191190.html

FrametSet中各frame,iframe之间dom的访问-->>http://www.cnblogs.com/hailexuexi/archive/2011/06/03/2072084.html

原文地址:https://www.cnblogs.com/simonbaker/p/3758644.html