使用postMessage进行iframe间通信

 arashilan 发布于 2023-02-07 12:06

我有域A的父页面(http://example.com)

在父页面上存在两个相同域但不是域A的iframe.(http://test.com)

当父是example.com时,有没有办法将值从一个test.com iframe传递给另一个,或者是我对iframe的"规则"描述的行为

谢谢

1 个回答
  • Checkout this JSFiddle, I simulated the cross-domain iFrames in order to make it more readable. Basically the top parent of both frames acts as a mediator to re-dispatch the message to the target frame, but the frames trigger all actions and responses.

    HTML

    <!-- Adding the sandboxing attribute to illustrade cross-domain -->
    <iframe id="one" sandbox="allow-scripts"></iframe>
    <iframe id="two" sandbox="allow-scripts"></iframe>
    

    JavaScript

    var frame_one = document.getElementById('one');
    var frame_two = document.getElementById('two');
    
    // The parent has to mediate because cross-domain sandboxing
    // is enabled when on different domains, plus backwards compatible.
    window.addEventListener('message', function (m) {
        // Using an object with a 'frame' property that maps to the ID
        // which could be done as you would like.
        var targetFrame = document.getElementById(m.data.frame);
        targetFrame.contentWindow.postMessage(m.data.message, '*');
    }, false);
    
    
    /**
     * This is just to illustrate what a normal document would look
     * like you should just set the normal 'src' attribute and the
     * string would be the normal HTML of the documents.
     */
    frame_two.srcdoc = '<!DOCTYPE html>\
    <html>\
    <head>\
    <script>\
    window.addEventListener("message", function (m) {\
    alert("Frame Two Says: " + m.data);\
    }, false);\
    window.addEventListener("load", function () {\
    window.parent.postMessage({frame: "one", message: "Received message from frame two!"}, "*");\
    }, false);\
    </script>\
    </head>\
    <body>\
    two\
    </body>';
    
    frame_one.srcdoc = '<!DOCTYPE html>\
    <html>\
    <head>\
    <script>\
    window.addEventListener("message", function (m) {\
    alert("Frame One Says: " + m.data);\
    }, false);\
    window.addEventListener("load", function () {\
    setTimeout(function () {\
    window.parent.postMessage({frame: "two", message: "Received message from frame one!"}, "*");\
    }, 1500);\
    }, false);\
    </script>\
    </head>\
    <body>\
    one\
    </body>';
    

    2023-02-07 12:08 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有