html5通过postMessage进行跨域通信的方法

2019-10-24

最近工作中遇到一个需求,场景是: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);
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

《html5通过postMessage进行跨域通信的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。