好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

HTML5中使用postMessage实现两个网页间传递数据

估计很少人知道HTML5 APIS里有一个window.postMessage API。window.postMessage的功能是允许程序员跨域在两个窗口/frames间发送数据信息。基本上,它就像是跨域的AJAX,但不是浏览器跟服务器之间交互,而是在两个客户端之间通信。让我们来看一下window.postMessage是如何工作的。除了IE6、IE7之外的所有浏览器都支持这个功能。
数据发送端
首先我们要做的是创建通信发起端,也就是数据源”source”。作为发起端,我们可以open一个新窗口,或创建一个iframe,往新窗口里发送数据,简单起见,我们每6秒钟发送一次,然后创建消息监听器,从目标窗口监听它反馈的信息。

//弹出一个新窗口   

    var domain = 'http://scriptandstyle.com';   

    var myPopup = window.open(domain    

                + '/windowPostMessageListener.html','myWindow');   

      

    //周期性的发送消息   

    setInterval(function(){   

     var message = 'Hello!  The time is: ' + (new Date().getTime());   

     console.log('blog.local:  sending message:  ' + message);   

            //send the message and target URI   

     myPopup.postMessage(message,domain);   

    },6000);   

      

    //监听消息反馈   

    window.addEventListener('message',function(event) {   

     if(event.origin !== 'http://scriptandstyle.com') return;   

     console.log('received response:  ',event.data);   

    },false); 
//捕获iframe   

    var domain = 'http://scriptandstyle.com';   

    var iframe = document.getElementById('myIFrame').contentWindow;   

      

    //发送消息   

    setInterval(function(){   

     var message = 'Hello!  The time is: ' + (new Date().getTime());   

     console.log('blog.local:  sending message:  ' + message);   

            //send the message and target URI   

     iframe.postMessage(message,domain);    

    },6000); 
//响应事件   

    window.addEventListener('message',function(event) {   

     if(event.origin !== 'http://davidwalsh.name') return;   

     console.log('message received:  ' + event.data,event);   

     event.source.postMessage('holla back youngin!',event.origin);   

    },false); 

以上就是HTML5中使用postMessage实现两个网页间传递数据 的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

-->

查看更多关于HTML5中使用postMessage实现两个网页间传递数据的详细内容...

  阅读:78次