怎么用h5的postMessage方法iframe跨域消息传递的问题

2023-05-16,,

这篇文章主要讲解了“怎么用h5postMessage方法iframe跨域消息传递的问题”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用h5的postMessage方法iframe跨域消息传递的问题”吧!

页面1 localhost:8086/index.html复制代码

<div >
        <div id="color">Frame Color</div>
    </div>
   <div>
       <iframe id="child" src="http://localhost:8087/index.html"></iframe>
      </div>
 
   <script type="text/javascript">
 
          window.οnlοad=function(){
             window.frames[0].postMessage('getcolor','http://localhost:8087');
           }
 
       window.addEventListener('message',function(e){
               var color=e.data;
              document.getElementById('color').style.backgroundColor=color;
     },false);
    </script>

页面2 localhost:8087/index.html

<body >
     <div id="container" οnclick="changeColor();" >
          click to change color
  </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;
              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>

在浏览器浏览 localhost:8086/index.html 点击iframe页面可以改变父类的颜色

就是这么easy

感谢各位的阅读,以上就是“怎么用h5的postMessage方法iframe跨域消息传递的问题”的内容了,经过本文的学习后,相信大家对怎么用h5的postMessage方法iframe跨域消息传递的问题这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是本站,小编将为大家推送更多相关知识点的文章,欢迎关注!

《怎么用h5的postMessage方法iframe跨域消息传递的问题.doc》

下载本文的Word格式文档,以方便收藏与打印。