zoukankan      html  css  js  c++  java
  • iframe之父子页面通信

    iframe之父子页面通信

    1、获取 子页面 的 window 对象 

    在父页面中,存在如下两个对象

    window.frames

    document.iframeElement.contentWindow

    可以获取到 子页面 window 对象

    // iframe id
    document.getElementById('menuIframe').contentWindow
    
    // iframe name
    window.frames['menuIframe'].window
    
    // iframe index 当前窗体的第几个 iframe
    window.frames[1].window

    既然拿到了 window 对象,那函数和DOM就到手了。

    2、子 iframe 获取 父页面

    window.parent 对象

    window.top对象

    // 判断当前页面是否是 iframe 或 顶级页面
    window.parent == window
    window.top == window

    window.parent 即为当前页面的上一级页面的 window 对象,如果当前页面已是 顶层 页面,则 window.parent 就是自己。

    3、小实例

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <iframe src="/sub.html" name="iframeContainer" id="iframeContainer"></iframe>
        <script type="text/javascript">
            function parentHello() {
                alert("this is parent hello function!");
            }
            window.frames['iframeContainer'].subHello();
        </script>
    </body>
    </html>
    
    <!-- sub.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <script type="text/javascript">
            function subHello() {
                alert("this is sub hello function!");
            }
    
            window.parent.parentHello();
        </script>
    </body>
    </html>
    

      

    转载自:https://my.oschina.net/sallency/blog/1618971

  • 相关阅读:
    蓝桥杯基础练习 杨辉三角形
    蓝桥杯基础练习 回文数 特殊的数字
    普及图论三题 P1807 P1113 P 4017
    P3916 图的遍历
    [转载][总结]图论入门:建图,DFS,BFS,拓扑排序
    如何转载博客园的文章
    P1892 [BOI2003]团伙
    P1621 集合
    [模板]线性筛素数(欧拉筛)
    P5076 普通二叉树(简化版)
  • 原文地址:https://www.cnblogs.com/s313139232/p/10430151.html
Copyright © 2011-2022 走看看