這里總結(jié)一下postMessage的使用,api很簡單:
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow是目標窗口的引用,在當前場景下就是iframe.contentWindow;
message是發(fā)送的消息,在Gecko 6.0之前,消息必須是字符串,而之后的版本可以做到直接發(fā)送對象而無需自己進行序列化;
targetOrigin表示設定目標窗口的origin,其值可以是字符串 * (表示無限制)或者一個URI。在發(fā)送消息的時候,如果目標窗口的協(xié)議、主機地址或端口這三者的任意一項不匹配targetOrigin提供的值,那么消息就不會被發(fā)送;只有三者完全匹配,消息才會被發(fā)送。對于保密性的數(shù)據(jù),設置目標窗口origin非常重要;
當postMessage()被調(diào)用的時,一個消息事件就會被分發(fā)到目標窗口上。該接口有一個message事件,該事件有幾個重要的屬性:
1.data:顧名思義,是傳遞來的message
2.source:發(fā)送消息的窗口對象
3.origin:發(fā)送消息窗口的源(協(xié)議+主機+端口號)
這樣就可以接收跨域的消息了,我們還可以發(fā)送消息回去,方法類似。
可選參數(shù)transfer 是一串和message 同時傳遞的 Transferable 對象. 這些對象的所有權(quán)將被轉(zhuǎn)移給消息的接收方,而發(fā)送一方將不再保有所有權(quán)。
那么,當iframe初始化后,可以通過下面代碼獲取到iframe的引用并發(fā)送消息:
// 注意這里不是要獲取iframe的dom引用,而是iframe window的引用const iframe = document.getElementById( myIFrame ).contentWindow;iframe.postMessage( hello world , http://yourhost.com
在iframe中,通過下面代碼即可接收到消息。
window.addEventListener( message , msgHandler, false);
在接收時,可以根據(jù)需要,對消息來源origin做一下過濾,避免接收到非法域名的消息導致的xss攻擊。
最后,為了代碼復用,把消息發(fā)送和接收封裝成一個類,同時模擬了消息類型的api,使用起來非常方便。具體代碼如下:
export default class Messager { constructor(win, targetOrigin) { this.win = win; this.targetOrigin = targetOrigin; this.actions = {}; window.addEventListener( message , this.handleMessageListener, false); handleMessageListener = event = { if (!event.data || !event.data.type) { return; const type = event.data.type; if (!this.actions[type]) { return console.warn(`${type}: missing listener`); this.actions[type](event.data.value); on = (type, cb) = { this.actions[type] = cb; return this; emit = (type, value) = { this.win.postMessage({ type, value }, this.targetOrigin); return this; destroy() { window.removeEventListener( message , this.handleMessageListener);}
以上內(nèi)容就是html5通過postMessage進行跨域通信的方法,希望能幫助到大家。
相關(guān)推薦:
HTML5中的postMessage API基本使用方法分享
HTML5中使用postMessage實現(xiàn)兩個網(wǎng)頁間傳遞數(shù)據(jù)
html5中postMessage實現(xiàn)Ajax中的POST跨域問題
以上就是html5通過postMessage進行跨域通信的方法的詳細內(nèi)容,其它編程語言
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。
新聞熱點
疑難解答