zoukankan      html  css  js  c++  java
  • html5 postMessage解决跨域、跨窗口消息传递

    问题:

    对于跨域问题,研究了一下html5的postMessage,写了代码测试了一下,感觉html5新功能就是好用啊。
    此文仅使用html5的新特性postMessage,演示其执行过程和效果:

    方法解释:
    postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。
    postMessage(data,origin)方法接受两个参数:
    1.data:你需要传递的消息,消息传递的格式有一定要求:参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以建议直接传递string类型参数。json格式使用JSON.stringify()方法对对象参数序列化,在低版本IE中引用json2.js可以实现类似效果。
    2.origin:该参数指明目标窗口的源。postMessage()方法只会将message传递给指定窗口,也可以设置为"*",表示可以传递给任意窗口。

    原理:

    1.我的页面是parent.html,接收我发送的消息并按照要求返回消息的页面是child.html;

    2.两个页面放在同一个文件夹内;

    3.parent.html发送postMessage消息给child.html,child.html收到消息后通过source.postMessage返回所需信息!

    具体过程如下:

    我的页面是parent.html:

    <html>
    <div>
        <iframe id="child" src="./child.html"></iframe>
    </div>
    <script type="text/javascript">
        window.addEventListener('message',function(e){
            alert("msg from child:" + e.data);
        });
        window.onload=function(){//页面加载完即向iframe发送消息
            //var tmp = document.getElementById("child");
            //tmp.postMessage('hello babi','*');  //此处tmp没有postMessage方法,类型错误。
            //alert(tmp); //这是object HTMLIFrameElement类型
            //alert(window.frames[0]);  //这是object Window类型
            //以上方式不可行,只有window类型才能调用postMessage方法!
            window.frames[0].postMessage('hello babi','*');
        }
    </script>
    </html>

    中间的文字全都来自child.html!

    我们看看接收消息页面child.html:

    parent页面向child页面发送了消息,那么在child页面上如何接收消息呢,监听window的message事件就可以

    <html>
    <p id="ll1">I'm child</p>
    <p id="ll2">I'm child</p>
    <p id="ll3">I'm child</p>
    <p id="ll4">I'm child</p>
    <script type="text/javascript">
        window.addEventListener('message',function(e){//接收信息后返回信息!
            alert("msg from parent:" + e.data);
            e.source.postMessage('Hello papi', "*");
        });
    </script>
    </html>

    这样我们就可以接收任何窗口传递来的消息了!

    我们运行一下:

    这样就实现了跨域、跨窗口消息传递

  • 相关阅读:
    转:python时间日期处理小结
    vi 的一些常用操作-君子善假于物也
    没有了老师,该如何学习?
    git常用命令
    python 读配置文件
    Python中unittest用法实例
    python 单元测试unnitest-摘录自http://www.cnblogs.com/hackerain/p/3682019.html#undefined
    纯CSS实现立方体旋转
    CSS 3动画
    CSS 2D转换
  • 原文地址:https://www.cnblogs.com/McQueen1987/p/3982765.html
Copyright © 2011-2022 走看看