欢迎光临成都祈钰瑶科技有限公司网站!祝您生活愉快!
热线电话: 18982081108
✕

成都服务器托管,成都GPU服务器租用,成都高防BGP宽带租用,成都机柜租用托管

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

这篇文章主要讲解了“怎么用h5的postMessage方法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跨域消息传递的问题这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!