国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > HTML > 正文

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

2024-08-26 00:20:55
字體:
來源:轉載
供稿:網友

本文介紹了詳解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('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>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到HTML教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 洞口县| 靖边县| 韩城市| 岳池县| 宜章县| 洮南市| 竹溪县| 康马县| 光山县| 鄂尔多斯市| 崇阳县| 文成县| 瑞丽市| 临漳县| 安塞县| 旬阳县| 正定县| 望城县| 高密市| 六枝特区| 西乡县| 叙永县| 马边| 胶州市| 剑河县| 海门市| 安康市| 乌拉特前旗| 枣阳市| 奉节县| 南雄市| 拉萨市| 鄂托克旗| 淳安县| 射阳县| 牡丹江市| 咸丰县| 额济纳旗| 巧家县| 山西省| 武鸣县|