怎么用h5的postMessage方法iframe跨域消息傳遞的問題

這篇文章主要講解了“怎么用h5的postMessage方法iframe跨域消息傳遞的問題”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“怎么用h5的postMessage方法iframe跨域消息傳遞的問題”吧!

創(chuàng)新互聯(lián)公司專注于嶺東網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供嶺東營(yíng)銷型網(wǎng)站建設(shè),嶺東網(wǎng)站制作、嶺東網(wǎng)頁設(shè)計(jì)、嶺東網(wǎng)站官網(wǎng)定制、微信平臺(tái)小程序開發(fā)服務(wù),打造嶺東網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供嶺東網(wǎng)站排名全網(wǎng)營(yíng)銷落地服務(wù)。

頁面1 localhost:8086/index.html復(fù)制代碼

<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 點(diǎn)擊iframe頁面可以改變父類的顏色

就是這么easy

感謝各位的閱讀,以上就是“怎么用h5的postMessage方法iframe跨域消息傳遞的問題”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)怎么用h5的postMessage方法iframe跨域消息傳遞的問題這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

新聞標(biāo)題:怎么用h5的postMessage方法iframe跨域消息傳遞的問題
瀏覽路徑:http://muchs.cn/article48/ihighp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、服務(wù)器托管、電子商務(wù)、網(wǎng)站制作、建站公司、網(wǎng)站營(yíng)銷

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化