最近工作中遇到一個需求,場景是:h5頁作為預覽模組內嵌在pc頁中,使用者在pc頁中能夠做一些操作,然後h5做出響應式變化,達到預覽的效果。
這裡首先想到就是把h5頁面用iframe內嵌到pc網頁中,然後pc透過postMessage方法,把變化的數據發送給iframe,iframe內嵌的h5透過addEventListener接收數據,再對數據做響應式的變化。
這裡總結一下postMessage的使用,api很簡單:
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow
是目標視窗的引用,在目前場景下是iframe.contentWindow;
message
是發送的訊息,在Gecko 6.0之前,訊息必須是字串,而之後的版本可以做到直接發送物件而無需自己進行序列化;
targetOrigin
表示設定目標視窗的origin,其值可以是字串*(表示無限制)或是一個URI。在傳送訊息的時候,如果目標視窗的協定、主機位址或連接埠這三者的任一項不符合targetOrigin提供的值,那麼訊息就不會被傳送;只有三者完全匹配,訊息才會被傳送。對於保密的數據,設定目標視窗origin非常重要;
當postMessage()被呼叫的時,一個訊息事件就會被分發到目標視窗上。該介面有一個message事件,該事件有幾個重要的屬性:
1.data:顧名思義,是傳遞來的message
2.source:發送訊息的視窗對象
3.origin:傳送訊息視窗的來源(協定+主機+連接埠號碼)
這樣就可以接收跨域的訊息了,我們還可以發送訊息回去,方法類似。
可選參數transfer 是一串和message 同時傳遞的Transferable 物件. 這些物件的所有權將轉移給訊息的接收方,而傳送一方將不再保有所有權。
那麼,當iframe
初始化後,可以透過下面程式碼取得到iframe的引用並發送訊息:
// 注意這裡不是要取得iframe的dom引用,而是iframe window的引用const iframe = document.getElementById('myIFrame').contentWindow;iframe.postMessage('hello world', 'http://yourhost.com' );
在iframe中,透過下面程式碼即可接收到訊息。
window.addEventListener('message', msgHandler, false);
在接收時,可以根據需要,對消息來源origin做一下過濾,避免接收到非法域名的消息導致的xss攻擊。
最後,為了程式碼重複使用,把訊息發送和接收封裝成一個類,同時模擬了訊息類型的api,使用起來非常方便。具體代碼如下:
export default class Messager { constructor(win, targetOrigin) { this.win = win; this.targetOrigin = targetOrigin; this.actions = {}; window.addEventListener('message', this.handleMessageList}; => { 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); }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。