最近工作中遇到一個需求,場景是: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.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);
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。