这篇文章主要为大家展示了“H5中window.postMessage与跨域的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“H5中window.postMessage与跨域的示例分析”这篇文章吧。

成都服务器托管,成都创新互联公司提供包括服务器租用、西部信息中心、带宽租用、云主机、机柜租用、主机租用托管、CDN网站加速、空间域名等业务的一体化完整服务。电话咨询:13518219792
HTML5 window.postMessage API
HTML5 window.postMessage是一个安全的、基于事件的消息API。
postMessage发送消息
在需要发送消息的源窗口调用postMessage方法即可发送消息。
源窗口
源窗口可以是全局的window对象,也可以是以下类型的窗口:
文档窗口中的iframe:
var iframe = document.getElementById('my-iframe');
    var win = iframe.documentWindow;JavaScript打开的弹窗:
var win = window.open();
当前文档窗口的父窗口:
var win = window.parent;
打开当前文档的窗口:
var win = window.opener();
找到源window对象后,即可调用postMessage API向目标窗口发送消息:
``win.postMessage('Hello', 'ttp://jhssdemo.duapp.com/');"postMessage函数接收两个参数:第一个为将要发送的消息,第二个为源窗口的源。
注:只有当目标窗口的源与postMessage函数中传入的源参数值匹配时,才能接收到消息。
接收postMessage消息
要想接收到之前源窗口通过postMessage发出的消息,只需要在目标窗口注册message事件并绑定事件监听函数,就可以在函数参数中获取消息。
window.onload = function() {
        var text = document.getElementById('txt');  
        function receiveMsg(e) {
            console.log("Got a message!");
            console.log("nMessage: " + e.data);
            console.log("nOrigin: " + e.origin);
            // console.log("Source: " + e.source);
            text.innerHTML = "Got a message!
" +
                "Message: " + e.data +
                "
Origin: " + e.origin;
        }
        if (window.addEventListener) {
            //为窗口注册message事件,并绑定监听函数
            window.addEventListener('message', receiveMsg, false);
        }else {
            window.attachEvent('message', receiveMsg);
        }
    };message事件监听函数接收一个参数,Event对象实例,该对象有三个属性:
- data 发送的具体消息 
- origin 发送消息源 
- source 发送消息窗口的window对象引用 
说明
- 可以将postMessage函数第二个参数设为*,在发送跨域消息时会跳过对发送消息的源的检查。 
- postMessage只能发送字符串信息。 
实例
源窗口
Html5 postMessage 
目标窗口win.html
Html5 postMessage The New Window
以上是“H5中window.postMessage与跨域的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
名称栏目:H5中window.postMessage与跨域的示例分析
标题链接:http://www.cqwzjz.cn/article/poejdg.html

 建站
建站
 咨询
咨询 售后
售后
 建站咨询
建站咨询 
 