JS之iframe

0.什么是iframe: iframe 元素会创建包含另外一个文档的内联框架(即行内框架)。

1. 获得iframe的window对象:(存在跨域访问限制)

chrome: iframeElement. contentWindow 
firefox:   iframeElement.contentWindow 
ie6:       iframeElement.contentWindow

function getIframeWindow(element){        
    return  element.contentWindow;
    //return  element.contentWindow || element.contentDocument.parentWindow;
}

2. 获得iframe的document对象:(存在跨域访问限制)

chrome:iframeElement.contentDocument
firefox:  iframeElement.contentDocument
ie:        element.contentWindow.document
备注:ie没有iframeElement.contentDocument属性。

var getIframeDocument = function(element) {
    return  element.contentDocument || element.contentWindow.document;
};

3. iframe中获得父页面的window对象:

   存在跨域访问限制。

   父页面:window.parent
   顶层页面:window.top
   适用于所有浏览器

4.同域下父子页面的通信

父页面parent.html:

<html>
<head>
    <script type="text/javascript">
        function say(){
            alert("parent.html");
        }
        function callChild(){
            myFrame.window.say();
            myFrame.window.document.getElementById("button").value="调用结束";
        }
    </script>
</head>
<body>
    <input id="button" type="button" value="调用child.html中的函数say()" onclick="callChild()"/>
    <iframe name="myFrame" src="child.html"></iframe>
</body>
</html>

子页面child.html:

<html>
<head>
    <script type="text/javascript">
        function say(){
            alert("child.html");
        }
        function callParent(){
            parent.say();
            parent.window.document.getElementById("button").value="调用结束";
        }
    </script>
</head>
<body>
    <input id="button" type="button" value="调用parent.html中的say()函数" onclick="callParent()"/>
</body>
</html>

方法调用

父页面调用子页面方法:FrameName.window.childMethod();

子页面调用父页面方法:parent.window.parentMethod();

DOM元素访问

获取到页面的window.document对象后,即可访问DOM元素

注意事项:

要确保在iframe加载完成后再进行操作,如果iframe还未加载完成就开始调用里面的方法或变量,会产生错误。判断iframe是否加载完成有两种方法

1. iframe上用onload事件

     补充:

     非ie浏览器都提供了onload事件。

var ifr = document.createElement('iframe');
ifr.src = 'http://www.b.com/index.php';
ifr.onload = function() {
    alert('loaded');
};
document.body.appendChild(ifr);

  实际上IE提供了onload事件,但必须使用attachEvent进行绑定。

var ifr = document.createElement('iframe');
ifr.src = 'http://b.a.com/b.php';
if (ifr.attachEvent) {
    ifr.attachEvent('onload',  function(){ alert('loaded'); });
} else {
    ifr.onload  = function() { alert('loaded'); };
}
document.body.appendChild(ifr);

2. 用document.readyState=="complete"来判断

五、跨域父子页面通信方法

如果iframe所链接的是外部页面,因为安全机制就不能使用同域名下的通信方式了。

1.父页面向子页面传递数据

实现的技巧是利用location对象的hash值,通过它传递通信数据。在父页面设置iframe的src后面多加个data字符串,然后在子页面中通过某种方式能即时的获取到这儿的data就可以了,例如:

1. 在子页面中通过setInterval方法设置定时器,监听location.href的变化即可获得上面的data信息

2. 然后子页面根据这个data信息进行相应的逻辑处理

2.子页面向父页面传递数据

实现技巧就是利用一个代理iframe,它嵌入到子页面中,并且和父页面必须保持是同域,然后通过它充分利用上面第一种通信方式的实现原理就把子页面的数据传递给代理iframe,然后由于代理的iframe和主页面是同域的,所以主页面就可以利用同域的方式获取到这些数据。使用 window.top或者window.parent.parent获取浏览器最顶层window对象的引用。

 

原文地址:https://www.cnblogs.com/boyangx/p/4509288.html