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

首頁 > 開發 > HTML5 > 正文

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

2024-09-05 07:22:36
字體:
來源:轉載
供稿:網友

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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 分宜县| 赤壁市| 宁德市| 普陀区| 繁昌县| 永胜县| 紫阳县| 平罗县| 随州市| 蒙自县| 麻城市| 上栗县| 西吉县| 武宣县| 合作市| 昭觉县| 通许县| 安义县| 尼玛县| 丹凤县| 勃利县| 湖北省| 浑源县| 古丈县| 青浦区| 衡阳市| 普宁市| 北海市| 云龙县| 德令哈市| 永登县| 甘谷县| 香港 | 文成县| 山西省| 斗六市| 瑞安市| 扶沟县| 滕州市| 将乐县| 武穴市|