postMessage实现父子页面简单通信

原文链接

关于postMessage的讲解可参考这里

github地址

demo演示

demo演示

代码片段

父页面

let HOST = 'http://localhost:8080/', //允许通信的域名
    rows = 0,
    cols = 0;

export default {
    data () {
        return {
            msg: '',
            msgList: [], //消息列表
            childWins: [] //子页面对象集合
        }
    },

    watch: {
        msgList () {
            let $toView = document.querySelector('.toView');
            $toView.scrollIntoView();
        }
    },

    methods: {
        send () {
            //发送消息
            if(this.msg == '') { return; }
            let msgObj = {
                msg: this.msg,
                sender: 'parent'
            };
            this.msgList.push(msgObj);
            for(let i = 0, len = this.childWins.length; i < len; i ++) {
                this.childWins[i].postMessage(JSON.stringify(msgObj), HOST);
            }
            this.msg = '';
        },

        open () {
            //生成子页面,依次展示
            let newWin = window.open('/#/2', '_blank', 'width=300,height=400,top=' + (10 + cols * 400) + ',left=' + (10 + rows * 300));
            this.childWins.push(newWin);
            cols ++;
            if(cols % 2 == 0) {
                rows ++;
                cols = 0;
            }
        }
    },

    mounted () {
        //监听消息
         window.addEventListener('message', e => {
            let msgObj = JSON.parse(e.data);
            this.msgList.push(msgObj);
        }, false);
    }
}
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

子页面

let HOST = 'http://localhost:8080/';

export default {
    data () {
        return {
            msg: '',
            msgList: []
        }
    },

    watch: {
        msgList () {
            let $toView = document.querySelector('.toView');
            $toView.scrollIntoView();
        }
    },

    methods: {
        send () {
            //发送消息
            if(this.msg == '') { return; }
            let msgObj = {
                msg: this.msg,
                sender: 'son'
            };
            this.msgList.push(msgObj);
            window.opener.postMessage(JSON.stringify(msgObj), HOST);
            this.msg = '';
        }
    },

    mounted () {
        //监听消息
        window.addEventListener('message', e => {
            let msgObj = JSON.parse(e.data);
            this.msgList.push(msgObj);
        }, false);
    }
}
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
36
37
38
39
最近更新: 9/13/2020, 10:47:04 PM