HTML5中window.postMessage与跨域的示例分析-创新互联

这篇文章给大家分享的是有关HTML5中window.postMessage与跨域的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

公司主营业务:成都做网站、网站设计、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联推出武都免费做网站回馈大家。

讲到浏览器同源策略,即阻止不同域的页面间访问彼此的方法和属性,并对解决同源策略跨域问题提出的解决方案进行阐述:子域代理、JSONP、CORS。本篇将详细阐述HTML5 window.postMessage,借助postMessage API,文档间可以以安全可控的方式实现跨域通信,第三方JavaScript代码也可以与iframe内加载的外部文档进行通信。

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!<br>" +
                "Message: " + e.data +
                "<br>Origin: " + e.origin;
        }
        if (window.addEventListener) {
            //为窗口注册message事件,并绑定监听函数
            window.addEventListener('message', receiveMsg, false);
        }else {
            window.attachEvent('message', receiveMsg);
        }
    };

message事件监听函数接收一个参数,Event对象实例,该对象有三个属性:

  1. data 发送的具体消息

  2. origin 发送消息源

  3. source 发送消息窗口的window对象引用

说明

  1. 可以将postMessage函数第二个参数设为*,在发送跨域消息时会跳过对发送消息的源的检查。

  2. postMessage只能发送字符串信息。

实例

源窗口

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Html5 postMessage</title>
        <style>
            #otherWin {
                width: 600px;
                height: 400px;
                background-color: #cccccc;
            }
        </style>
    </head>
    <body>
        <button id="btn">open</button>
        <button id="send">send</button>
         <!-- 通过 iframe 嵌入子页面(接收消息目标窗口) --> 
         <iframe src="http://jhssdemo.duapp.com/demo/h6_postmessage/win.html" 
                     id="otherWin"></iframe> 
         <br/><br/> 
         <input type="text" id="message"><input type="button" 
                 value="Send to child.com" id="sendMessage" /> 
        <script>
            window.onload = function() {
                var btn = document.getElementById('btn');
                var btn_send = document.getElementById('send');
                var sendBtn = document.getElementById('sendMessage');
                var win;
                btn.onclick = function() {
                    //通过window.open打开接收消息目标窗口
                    win = window.open('http://jhssdemo.duapp.com/demo/h6_postmessage/win.html', 'popUp');
                }
                btn_send.onclick = function() { 
                    // 通过 postMessage 向子窗口发送数据      
                    win.postMessage('Hello', 'http://jhssdemo.duapp.com/');
                }
                function sendIt(e){ 
                    // 通过 postMessage 向子窗口发送数据
                    document.getElementById("otherWin").contentWindow 
                    .postMessage( 
                        document.getElementById("message").value, 
                        "http://jhssdemo.duapp.com/"); 
                } 
                sendBtn.onclick = function(e) {
                    sendIt(e);
                };
            };
        </script>
    </body>
    </html>

目标窗口win.html

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Html5 postMessage</title>
        <style>
            #txt {
                width: 500px;
                height: 300px;
                background-color: #cccccc;
            }
        </style>
    </head>
    <body>
        <h2>The New Window</h2>
        <p id="txt"></p>
        <script>        
            window.onload = function() {
                var text = document.getElementById('txt');  
                //监听函数,接收一个参数--Event事件对象
                function receiveMsg(e) {
                    console.log("Got a message!");
                    console.log("nMessage: " + e.data);
                    console.log("nOrigin: " + e.origin);
                    text.innerHTML = "Got a message!<br>" +
                        "Message: " + e.data +
                        "<br>Origin: " + e.origin;
                }
                if (window.addEventListener) {
                    //为window注册message事件并绑定监听函数
                    window.addEventListener('message', receiveMsg, false);
                }else {
                    window.attachEvent('message', receiveMsg);
                }
            };
        </script>
    </body>
    </html>

感谢各位的阅读!关于“HTML5中window.postMessage与跨域的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。

本文标题:HTML5中window.postMessage与跨域的示例分析-创新互联
标题来源:https://www.cdcxhl.com/article0/diegio.html

成都网站建设公司_创新互联,为您提供企业网站制作全网营销推广网站导航微信小程序网站排名网站制作

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

网站建设网站维护公司