扣丁學堂HTML5培訓詳解HTML5 postMessage解決跨域通訊的問題

本篇文章扣丁學堂HTML5培訓小編給讀者們分享一下HTML5 postMessage解決跨域通訊的問題,文中有代碼列出供小夥伴們參考,感興趣的小夥伴就隨小編來了解一下吧。javascript

otherWindow:其餘窗口的一個引用, 好比IFRAME的contentWindow屬性, 執行,window.open返回的窗口對象。css

message:將要發送到其餘窗口的數據。html

targetOrigin:經過窗口的origin屬性來指定哪些窗口能接收到消息事件, 其值能夠是字符」*」(表示無限制)或者一個URL。java

transfer:是一串和message同時傳遞的Transferable對象。跨域

這些對象的全部權將被轉移給消息的接收方, 而發送一放將再也不保有全部權.element.addEventListener(event,fn,useCaption ); 三個參數 event 事件 好比click mouseenter mouseleave 回調函數 useCaption用於描述是冒泡仍是捕獲。默認值是false,即冒泡傳遞。 當值爲true,就是捕獲傳遞。微信

實現方式:函數

主界面 main.htmlpost

<!DOCTYPE html>學習

<html lang="en">ui

<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('message',function(e){

      console.log("e--->",e);

      const data = e.data;

      document.getElementById('main1').style.backgroundColor=e.data;

    },false)

</script>

</head>

<body>

<div id="main1" style="width:200px;height:200px;margin:100px;border:solid 1px #000;">

我是主界面,等待接收iframe的傳遞

</div>

<div style="margin:100px;">

iframe

<iframe src="http://localhost:3000/iframe.html" width="800px" height="300px" ></iframe>

</div>

</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%;">

<div id="frame" style="height:200px; width:200px;background-color:rgb(204, 204, 0)" onclick="changeColor()">

      點擊改變顏色

    </div>

    <script type="text/javascript">

        function changeColor(){

          var frame = document.getElementById('frame');

          var color=frame.style.backgroundColor;

          if(color=='rgb(204, 102, 0)'){

              color='rgb(204, 204, 0)';

          }else{

              color='rgb(204,102,0)';

          }

            console.log("frame===>",frame);

            console.log("color",color);

          frame.style.backgroundColor=color;

          window.parent.postMessage(color,'*');

        }

    </script>

</body>

</html>

想要了解更多關於HTML5方面內容的小夥伴,請關注扣丁學堂HTML5培訓官網、微信等平臺,扣丁學堂IT職業在線學習教育平臺爲您提供權威的HTML5視頻,HTML5培訓後的前景無限,行業薪資和將來的發展會愈來愈好的,扣丁學堂老師精心推出的HTML5視頻教程定能讓你快速掌握HTML5從入門到精通開發實戰技能。

相關文章
相關標籤/搜索