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

postmate

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

详细的使用见 示例

postmate的不足

  • 不支持直接配置iframe dom节点,而是postmate内部根据url在容器(container配置项)中创建iframe;
  • 不支持一个页面里配置多个子页面进行通信;
  • 不支持通过window.open的方式打开新页面后的通信;
  • postmates-js的改进

  • 支持直接配置iframe dom节点,而postmate内部是根据url在容器(container配置项)中创建iframe;
  • 支持一个页面里配置多个子页面进行通信;
  • 支持通过window.open的方式打开新页面后的通信;
  • <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)