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