postmates-js——用于iframe、新窗口等形式的父子

2021-11-15  本文已影响0人  videring

postmate

postmate是一款基于postMessage来处理父子页面通信的库,轻量且好用。

详细的使用见示例

postmate的不足

postmates-js的改进

支持一对多

源码

https://gitee.com/videring/postmates-js

使用方式

尽可能的少改动postmate的原有用法。
parent.com

<body>
    <div>Parent Page/div>
    <iframe id='cid1' style="width: 300px; height: 300px;" src="http://localhost:8081/c1.html"></iframe>
    <div id='cid2' style="width: 300px; height: 300px;"></div>
</body>
// Kick off the handshake with the iFrame
PostmatesJS.debug = true;
const open = window.open('http://localhost:8083/c3.html', '_blank')
const handshake = new PostmatesJS([
    {
        container: document.getElementById("cid1"), // first way
        url: "",
        name: "name1"
    }, {
        container: document.getElementById("cid2"), // second way, similar to `postmate`
        url: "http://localhost:8082/c2.html",
        name: "name2"
    }, {
        container: open, // document.getElementById("cid2"), // third way, open a new page with `window.open` 
        url: "http://localhost:8083/c3.html",
        name: "name2"
    }
]);

// When parent <-> child handshake is complete, data may be requested from the child
handshake.then(parentAPIs => {
    parentAPIs.forEach(parentAPI => {
        parentAPI.on('some-event', data => {
            console.log(data)
        }); // Logs "Hello, World!"
        parentAPI.call("demoFunction", {options:"Hello, PostmatesJS!"})
    })
});

localhost:8081/c1.html

PostmatesJS.debug = true
const model = new PostmatesJS.Model({
    demoFunction:(options) =>{
        console.log('child1', options)
    }
 });
model.then(childAPI => {
    childAPI.emit('some-event', 'Hello, World! Child1');
});

localhost:8082/c2.html

PostmatesJS.debug = true
const model = new PostmatesJS.Model({
    //demoFunction:提供给父页面的方法
    //options: 从父页面传入的参数信息
    demoFunction:(options) =>{
        console.log('child2', options)
    }
});
model.then(childAPI => {
    childAPI.emit('some-event', 'Hello, World! Child2');
});

localhost:8083/c3.html

PostmatesJS.debug = true
const model = new PostmatesJS.Model({
    //demoFunction:提供给父页面的方法
    //options: 从父页面传入的参数信息
    demoFunction:(options) =>{
        console.log('child3', options)
    }
});
model.then(childAPI => {
    childAPI.emit('some-event', 'Hello, World! Child3');
});
上一篇下一篇

猜你喜欢

热点阅读