• iframe子页面与父页面之间通信


    一、同域下父子页面的通信

    父页面parent.html

    <html>
    <head>
        <script type="text/javascript">
            function say(){
                alert("parent.html");
            }
            function callChild(){
                myFrame.say();
                myFrame.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事件

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

    例子:iframe子页面让父页面跳转

    parent页面

    <div>
        <iframe src="child.html"></iframe>
    </div>

    child页面

    里面有一个按钮,点击跳转页面,如果直接写location.href ='',还是在iframe中

    如果跳转的页面不想在iframe中,可以加一个parent

    <p class="clickGoTotalhtml" onclick="parent.location.href='welcome_total.html'">统计数据</p>

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

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

    父页面向子页面传递数据

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

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

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

    子页面向父页面传递数据

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

  • 相关阅读:
    hadoop集群无法找到datanode节点问题解决
    Startup.A51说明(上)
    UCOSII基础之数据结构
    FPGA之难度
    UCOSII学习笔记【二】
    (转)PCB中各层的含义(protel中)
    UCOSII学习笔记 一
    查看51汇编,解决奇怪的问题
    滑雪
    HMM的理解
  • 原文地址:https://www.cnblogs.com/samve/p/13263374.html
Copyright © 2020-2023  润新知