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

首頁 > 編程 > HTML > 正文

HTML5的postMessage的使用手冊

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

我們在碼代碼的時候,經常會碰到以下跨域的情況:

1、頁面內嵌套iframe,與iframe的消息傳遞

2、頁面與多個頁面之間的傳遞消息

針對這些令人頭疼的跨域問題,html5特地推出新功能--postMessage(跨文檔消息傳輸)。postMessage在使用時,需要傳入2個參數,data和originUrl。data是指需要傳遞的內容,但是部分瀏覽器只能處理字符串參數,所以我們一般把data序列化一下,即JSON.stringify(),originUrl是指目標url,指定的窗口。

下面直接甩例子,相信大家更容易理解寫。

1、頁面內嵌套iframe

父頁面:

html:

<div id='parent'>hello word postMessage</div><iframe src="http://127.0.0.1:8082/index2.html" id='child'></iframe>

js:

window.onload=function(){    window.frames[0].postMessage('postMessage','http://127.0.0.1:8082/index2.html')} window.addEventListener('message',function(e){    console.log(e)    document.getElementById('parent').style.color=e.data})

子頁面:

html:

<div id='button' onclick='changeColor();' style="color:yellow">接受信息</div>

js:

window.addEventListener('message',function(e){      console.log(e)      let color = document.getElementById('button').style.color      window.parent.postMessage(color,'http://127.0.0.1:8081/index.html')});function changeColor(){      let buttonColor = document.getElementById('button').style.color      buttonColor='#f00'                 window.parent.postMessage(buttonColor,'http://127.0.0.1:8081/index.html')}

父頁面通過postMessage的方法向iframe傳遞消息,而子頁面通過window.addEventListener監聽message方法來獲取到父頁面傳遞的值。如下圖所示,data是父頁面傳遞的值。

HTML5,postMessage,使用手冊

子頁面向父頁面傳遞消息,也是通過postMessage的方法去傳遞消息,不是過是以window.parent.postMessage(data,url)的方式傳值。父頁面獲取值也是同樣監聽message事件。

2、多頁面之間傳遞消息

父頁面:

html:

<div id='parent' onclick="postMessage()">hello word postMessage</div>

js:

let parent = document.getElementById('parent')function postMessage(){    let windowOpen=window.open('http://127.0.0.1:8082/index2.html','postMessage')    setTimeout(function(){       windowOpen.postMessage('postMessageData','http://127.0.0.1:8082/index2.html')  },1000) }

子頁面:

html:

<div id='button' onclick='changeColor();' style="color:#f00">接受信息</div>

js:

window.addEventListener('message',function(e){      console.log(e) });

父頁面向子頁面傳遞消息通過window.open打開另一個頁面,然后向他傳值。需要注意的是,使用postMessage傳值的時候需要使用setTimeout去延遲消息的傳遞,因為子頁面的加載不是一下子就加載完成的,也就是說子頁面的監聽事件還未開始,此時傳值過去是接收不到的。

HTML5,postMessage,使用手冊

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


注:相關教程知識閱讀請移步到HTML教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 商洛市| 马龙县| 烟台市| 凤翔县| 郓城县| 治多县| 博爱县| 辽源市| 湘乡市| 华宁县| 富锦市| 盐城市| 侯马市| 申扎县| 平乐县| 吴江市| 吉木萨尔县| 晋宁县| 社旗县| 定西市| 宜君县| 冷水江市| 芮城县| 铜梁县| 平乐县| 灵武市| 南投县| 静安区| 札达县| 泸定县| 乐业县| 漳浦县| 来凤县| 邵东县| 沂南县| 磐石市| 基隆市| 屏南县| 乐东| 保定市| 永寿县|