首頁  >  文章  >  web前端  >  詳解html5 postMessage解決跨域通訊的問題

詳解html5 postMessage解決跨域通訊的問題

青灯夜游
青灯夜游轉載
2018-10-09 16:09:251976瀏覽

這篇文章主要介紹了詳解html5 postMessage解決跨域通訊的問題的相關資料,有一定的參考價值,有需要的朋友可以參考一下,希望對你們有所幫助。

本文介紹了詳解html5 postMessage解決跨域通訊的問題,分享給大家,具體如下:

效果圖:

postmessage解析HTML5提供了新型機制PostMessage實作安全的跨來源通訊. 

語法:

otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow:其他視窗的一個引用, 例如IFRAME的contentWindow屬性, 執行,window.open的視窗對象。

message:將要傳送到其他視窗的資料。

targetOrigin:透過視窗的origin屬性來指定哪些視窗能接收到訊息事件, 其值可以是字元」*」(表示無限制)或是一個URL transfer:是一串和message同時傳遞的Transferable對象。這些物件的所有權將被轉移給訊息的接收方, 而發送一放將不再保有所有權。

element.addEventListener(event,fn,useCaption ); 三個參數 event 事件 例如click mouseenter mouseleave 回呼函數 useCaption用來描述是冒泡還是捕獲。預設值是false,即冒泡傳遞。當值為true,就是捕獲傳遞。實作方式

主介面 main.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>跨域数据访问</title>
  <script type="text/javascript">
         window.addEventListener(&#39;message&#39;,function(e){
           console.log("e--->",e);
           const data = e.data;
           document.getElementById(&#39;main1&#39;).style.backgroundColor=e.data;
         },false)

  </script>
</head>
<body>
  <p id="main1" style="width:200px;height:200px;margin:100px;border:solid 1px #000;">
     我是主界面,等待接收iframe的传递
  </p>
  <p style="margin:100px;">
     iframe
     <iframe src="http://localhost:3000/iframe.html" width="800px" height="300px" ></iframe>
  </p>
</body>
</html>

iframe介面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
    <style type="text/css">
           html,body{
               height:100%;
               margin:0px;
           }
    </style>
</head>
  <body style="height:100%;">
        <p id="frame" style="height:200px; width:200px;background-color:rgb(204, 204, 0)" onclick="changeColor()">
           点击改变颜色
        </p>
        <script type="text/javascript">
             function changeColor(){
               var frame = document.getElementById(&#39;frame&#39;);
               var color=frame.style.backgroundColor;
               if(color==&#39;rgb(204, 102, 0)&#39;){
                   color=&#39;rgb(204, 204, 0)&#39;;
               }else{
                   color=&#39;rgb(204,102,0)&#39;;
               }
                console.log("frame===>",frame);
                console.log("color",color);
               frame.style.backgroundColor=color;
               window.parent.postMessage(color,&#39;*&#39;);
             }
        </script>
  </body>
</html>

總結:以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。更多相關教學請造訪Html5影片教學

相關推薦:

php公益訓練影片教學

#HTML5圖文教學

HTML5線上手冊

以上是詳解html5 postMessage解決跨域通訊的問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:jb51.net。如有侵權,請聯絡admin@php.cn刪除