您好,登錄后才能下訂單哦!
本篇文章為大家展示了postMessage如何在HTML5中使用,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
1、頁面內(nèi)嵌套iframe,與iframe的消息傳遞
2、頁面與多個頁面之間的傳遞消息
針對這些令人頭疼的跨域問題,html5特地推出新功能--postMessage(跨文檔消息傳輸)。postMessage在使用時,需要傳入2個參數(shù),data和originUrl。data是指需要傳遞的內(nèi)容,但是部分瀏覽器只能處理字符串參數(shù),所以我們一般把data序列化一下,即JSON.stringify(),originUrl是指目標(biāo)url,指定的窗口。
下面直接甩例子,相信大家更容易理解寫。
1、頁面內(nèi)嵌套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去延遲消息的傳遞,因?yàn)樽禹撁娴募虞d不是一下子就加載完成的,也就是說子頁面的監(jiān)聽事件還未開始,此時傳值過去是接收不到的。
上述內(nèi)容就是postMessage如何在HTML5中使用,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。