html5 postMessage解决跨域、跨窗口消息传递

html5 postMessage解决跨域、跨窗口消息传递更多

  • 1.html

 <html>
 <head>
     <title>Post Message</title>
 </head>
 <body>
     <div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;">
         <div id="color">1.html </div>
     </div>
     <div>
         <iframe id="child" src="2.html"></iframe>
     </div>
 
     <script type="text/javascript">
  
         window.addEventListener('message',function(e){
             var color=e.data;
			 debugger
             document.getElementById('color').style.backgroundColor=color;
         },false);
     </script>
 </body>
 </html>
  • 2.html
<body style="height:100%;">
         <div id="container" onclick="changeColor();" style="widht:100%; height:100%; background-color:rgb(204, 102, 0);">
             iframe 2.html 
         </div>
         <script type="text/javascript">
             var container=document.getElementById('container');
 
           /*  window.addEventListener('message',function(e){
                 if(e.source!=window.parent) return;
                 var color=container.style.backgroundColor;
				 debugger
                 window.parent.postMessage(color,'*');
             },false);*/
 
             function changeColor () {            
                 var color=container.style.backgroundColor;
                 if(color=='rgb(204, 102, 0)'){
                     color='rgb(204, 204, 0)';
                 }else{
                     color='rgb(204,102,0)';
                 }
                 container.style.backgroundColor=color;
                 window.parent.postMessage(color,'*');//人为触发
             }
         </script>
     </body>

posted on 2024-04-23 08:17  anjun_xf  阅读(24)  评论(0)    收藏  举报

导航

TOP