婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > HTML5的postMessage的使用手冊

HTML5的postMessage的使用手冊

熱門標簽:地圖標注軟件打印出來 欣鼎電銷機器人 效果 電話機器人技術 黃石ai電銷機器人呼叫中心 惡搞電話機器人 ok電銷機器人 高德地圖標注商戶怎么標 智能電銷機器人被禁用了么 如何查看地圖標注

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

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

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

針對這些令人頭疼的跨域問題,html5特地推出新功能--postMessage(跨文檔消息傳輸)。postMessage在使用時,需要傳入2個參數(shù),data和originUrl。data是指需要傳遞的內容,但是部分瀏覽器只能處理字符串參數(shù),所以我們一般把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監(jiān)聽message方法來獲取到父頁面?zhèn)鬟f的值。如下圖所示,data是父頁面?zhèn)鬟f的值。

子頁面向父頁面?zhèn)鬟f消息,也是通過postMessage的方法去傳遞消息,不是過是以window.parent.postMessage(data,url)的方式傳值。父頁面獲取值也是同樣監(jiān)聽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)

 });

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

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

標簽:中山 萍鄉(xiāng) 阿壩 聊城 綏化 金昌 赤峰 盤錦

巨人網(wǎng)絡通訊聲明:本文標題《HTML5的postMessage的使用手冊》,本文關鍵詞  HTML5,的,postMessage,使用手冊,;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《HTML5的postMessage的使用手冊》相關的同類信息!
  • 本頁收集關于HTML5的postMessage的使用手冊的相關信息資訊供網(wǎng)民參考!
  • 推薦文章
    主站蜘蛛池模板: 洱源县| 宁蒗| 普兰县| 灵台县| 睢宁县| 九龙坡区| 绿春县| 双辽市| 高尔夫| 长岭县| 庄浪县| 宜州市| 健康| 虞城县| 齐齐哈尔市| 岳西县| 吉木萨尔县| 观塘区| 冀州市| 鸡东县| 玛曲县| 曲麻莱县| 化德县| 徐州市| 嵊泗县| 禹州市| 兴海县| 桦川县| 南雄市| 乡城县| 安阳市| 固安县| 苏尼特左旗| 皋兰县| 厦门市| 兴隆县| 克东县| 大竹县| 嘉祥县| 分宜县| 来凤县|