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

首頁(yè) > 開(kāi)發(fā) > HTML5 > 正文

HTML5的postMessage的使用手冊(cè)

2024-09-05 07:22:45
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

我們?cè)诖a代碼的時(shí)候,經(jīng)常會(huì)碰到以下跨域的情況:

1、頁(yè)面內(nèi)嵌套iframe,與iframe的消息傳遞

2、頁(yè)面與多個(gè)頁(yè)面之間的傳遞消息

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

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

1、頁(yè)面內(nèi)嵌套iframe

父頁(yè)面:

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})

子頁(yè)面:

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')}

父頁(yè)面通過(guò)postMessage的方法向iframe傳遞消息,而子頁(yè)面通過(guò)window.addEventListener監(jiān)聽(tīng)message方法來(lái)獲取到父頁(yè)面?zhèn)鬟f的值。如下圖所示,data是父頁(yè)面?zhèn)鬟f的值。

子頁(yè)面向父頁(yè)面?zhèn)鬟f消息,也是通過(guò)postMessage的方法去傳遞消息,不是過(guò)是以window.parent.postMessage(data,url)的方式傳值。父頁(yè)面獲取值也是同樣監(jiān)聽(tīng)message事件。

2、多頁(yè)面之間傳遞消息

父頁(yè)面:

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) }

子頁(yè)面:

html:

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

js:

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

父頁(yè)面向子頁(yè)面?zhèn)鬟f消息通過(guò)window.open打開(kāi)另一個(gè)頁(yè)面,然后向他傳值。需要注意的是,使用postMessage傳值的時(shí)候需要使用setTimeout去延遲消息的傳遞,因?yàn)樽禹?yè)面的加載不是一下子就加載完成的,也就是說(shuō)子頁(yè)面的監(jiān)聽(tīng)事件還未開(kāi)始,此時(shí)傳值過(guò)去是接收不到的。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 晋宁县| 静乐县| 台中市| 肇东市| 罗平县| 濮阳市| 栾川县| 抚顺市| 巨野县| 垫江县| 新巴尔虎左旗| 迁安市| 资兴市| 准格尔旗| 衡南县| 明光市| 苗栗县| 凤翔县| 扶风县| 寻乌县| 仪征市| 睢宁县| 平遥县| 廉江市| 焉耆| 广西| 扶绥县| 杭锦旗| 霍邱县| 宁国市| 淮北市| 红安县| 津市市| 湛江市| 延寿县| 荃湾区| 汨罗市| 永济市| 阿荣旗| 苏州市| 长汀县|