postmate
postmate是一款基于postMessage來處理父子頁面通信的庫,輕量且好用。
詳細(xì)的使用見示例
postmate的不足
- 不支持直接配置iframe dom節(jié)點(diǎn),而是postmate內(nèi)部根據(jù)url在容器(container配置項(xiàng))中創(chuàng)建iframe;
- 不支持一個(gè)頁面里配置多個(gè)子頁面進(jìn)行通信;
- 不支持通過window.open的方式打開新頁面后的通信;
postmates-js的改進(jìn)
- 支持直接配置iframe dom節(jié)點(diǎn),而postmate內(nèi)部是根據(jù)url在容器(container配置項(xiàng))中創(chuàng)建iframe;
- 支持一個(gè)頁面里配置多個(gè)子頁面進(jìn)行通信;
- 支持通過window.open的方式打開新頁面后的通信;
支持一對(duì)多
源碼
https://gitee.com/videring/postmates-js
使用方式
盡可能的少改動(dòng)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: 從父頁面?zhèn)魅氲膮?shù)信息
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: 從父頁面?zhèn)魅氲膮?shù)信息
demoFunction:(options) =>{
console.log('child3', options)
}
});
model.then(childAPI => {
childAPI.emit('some-event', 'Hello, World! Child3');
});