最近工作中遇到一個(gè)需求,場景是:h5頁作為預(yù)覽模塊內(nèi)嵌在pc頁中,用戶在pc頁中能夠做一些操作,然后h5做出響應(yīng)式變化,達(dá)到預(yù)覽的效果。
這里首先想到就是把h5頁面用iframe內(nèi)嵌到pc網(wǎng)頁中,然后pc通過postMessage方法,把變化的數(shù)據(jù)發(fā)送給iframe,iframe內(nèi)嵌的h5通過addEventListener接收數(shù)據(jù),再對數(shù)據(jù)做響應(yīng)式的變化。
這里總結(jié)一下postMessage的使用,api很簡單:
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow
是目標(biāo)窗口的引用,在當(dāng)前場景下就是iframe.contentWindow;
message
是發(fā)送的消息,在Gecko 6.0之前,消息必須是字符串,而之后的版本可以做到直接發(fā)送對象而無需自己進(jìn)行序列化;
targetOrigin
表示設(shè)定目標(biāo)窗口的origin,其值可以是字符串"*"(表示無限制)或者一個(gè)URI。在發(fā)送消息的時(shí)候,如果目標(biāo)窗口的協(xié)議、主機(jī)地址或端口這三者的任意一項(xiàng)不匹配targetOrigin提供的值,那么消息就不會被發(fā)送;只有三者完全匹配,消息才會被發(fā)送。對于保密性的數(shù)據(jù),設(shè)置目標(biāo)窗口origin非常重要;
當(dāng)postMessage()被調(diào)用的時(shí),一個(gè)消息事件就會被分發(fā)到目標(biāo)窗口上。該接口有一個(gè)message事件,該事件有幾個(gè)重要的屬性:
1.data:顧名思義,是傳遞來的message
2.source:發(fā)送消息的窗口對象
3.origin:發(fā)送消息窗口的源(協(xié)議+主機(jī)+端口號)
這樣就可以接收跨域的消息了,我們還可以發(fā)送消息回去,方法類似。
可選參數(shù)transfer 是一串和message 同時(shí)傳遞的 Transferable 對象. 這些對象的所有權(quán)將被轉(zhuǎn)移給消息的接收方,而發(fā)送一方將不再保有所有權(quán)。
那么,當(dāng)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);
在接收時(shí),可以根據(jù)需要,對消息來源origin做一下過濾,避免接收到非法域名的消息導(dǎo)致的xss攻擊。
最后,為了代碼復(fù)用,把消息發(fā)送和接收封裝成一個(gè)類,同時(shí)模擬了消息類型的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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。