• iframe与主窗口通信


    1. 引言

    -->

    <div id="panel">
    <h3>主窗口h3>
    <code>code>
    div>
    div>
    <script>
    const parentMessage = {
    name: '李四',
    age: 20
    };
    // 建立握手程序
    const handshake = new Postmate({
    container: document.querySelector('#parent'), // 注意将原iframe注释掉
    url: './children.html'
    });
    // 握手成功后
    handshake.then(child => {
    // 监听事件
    child.on('some-event', data => console.log(data)); // Logs "Hello, World!"
    // 远程调用函数,将主窗口传给iframe的数据作为函数的参数
    child.call('changeParentMessage', parentMessage);
    // 获取数据
    child.get('childMessage').then(data => {
    document.querySelector('code').innerHTML = JSON.stringify(data)
    });
    });
    script>

    children.html:

    <script src="https://cdn.jsdelivr.net/npm/postmate@1.5.2/build/postmate.min.js">script>
    <div id="container">
    <h3>子窗口h3>
    <code>code>
    div>
    <script>
    const childMessage = {
    name: '张三',
    age: 18
    };
    const handshake = new Postmate.Model({
    // 建立握手模型 Property values may be functions, promises, or regular values
    childMessage: childMessage,
    parentMessage: {},
    changeParentMessage: function (newMessage) {
    this.parentMessage = newMessage;
    document.querySelector('code').innerHTML = JSON.stringify(this.parentMessage);
    }
    });
    //成功握手后可向主窗口触发事件
    handshake.then(parent => {
    parent.emit('some-event', 'Hello, World!');
    });
    script>

    结果如下:

    image-20230727020851043

    5. 参考资料

    [1]