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


当前第2页 返回上一页

最后,为了代码复用,把消息发送和接收封装成一个类,同时模拟了消息类型的api,使用起来非常方便。具体代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

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进行跨域通信的方法,希望能帮助到大家。

相关推荐:

HTML5中的postMessage API基本使用方法分享

HTML5中使用postMessage实现两个网页间传递数据

html5中postMessage实现Ajax中的POST跨域问题

以上就是html5通过postMessage进行跨域通信的方法的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

h5里的postmessage api图文详解 详细介绍

什么是html h1标签?html h1标签使用方法的详细介绍

html5应用-生日快乐动画的实现

移动端页面头部固定定位的绝对定位实现(代码示例)

html5 canvas

html5实现一个简单的多人飞机游戏实例详解

后盾网html5视频教程

h5的文本格式化使用方法

动手打造html5俄罗斯方块的(图文)

html5中overflow是什么意思

更多相关阅读请进入《postmessage》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...