h5的postMessage方法解决iframe跨域消息传递的问题

本文介绍了一种通过iframe实现父子窗口间颜色信息交互的方法。点击子窗口中的元素,父窗口中指定区域的颜色会随之变化,展示了PostMessage API的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

<div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;">
        <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 style="height:100%;">
     <div id="container" οnclick="changeColor();" style="widht:100%; height:100%; background-color:rgb(204, 102, 0);">
          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

转载于:https://my.oschina.net/u/588516/blog/3081898

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值