【问题标题】:iframe cross domain messaging with jQuery postMessage plugin使用 jQuery postMessage 插件的 iframe 跨域消息传递
【发布时间】:2012-06-11 11:15:14
【问题描述】:

我正在尝试使用以下插件在子 iframe 与其父级之间进行通信:

http://benalman.com/projects/jquery-postmessage-plugin/

我可以按照示例从孩子向父母发送消息,但不能相反,我真的需要能够以两种方式进行交流。

parent上的代码如下:

var origin = document.location.protocol + '//' + document.location.host,
    src = origin + '/Custom/Ui/Baseline/html/iframe-data-cash.htm#' + encodeURIComponent(document.location.href);

$(function () {

    var $holder = $('#iframe'),
        height,
        $iframe = $('<iframe src="' + src + '" id="data-cash-iframe" width="100%" scrolling="no" allowtransparency="true" seamless="seamless" frameborder="0" marginheight="0" marginwidth="0"></iframe>');

    // append iframe to DOM
    $holder.append($iframe);

});

$(window).load(function () {
    $.postMessage(
        'hello world',
        src,
        parent.document.getElementById('data-cash-iframe').contentWindow
    );
});

而孩子身上的代码如下:

$(function () {

    var parentURL = decodeURIComponent(document.location.hash.replace(/^#/, ''));

    $.receiveMessage(
        function (e) {
            alert(e.data);
        },
        parentURL
    );

});

我真的不明白为什么这不起作用,我迫切需要帮助!

【问题讨论】:

    标签: jquery jquery-plugins iframe cross-domain postmessage


    【解决方案1】:
    1.sendPage
    <script type='text/javascript'>
    var sendpost = document.getElementById('wrapper').scrollHeight;
    var target = parent.postMessage ? parent : (parent.document.postMessage ?   parent.document : undefined); 
    target.postMessage(sendpost,'*');
    </script>
    2. real iframe load page
    function handling(e){
                    sendIframeHeight = e.data;
    }
    
    // <= ie8
    if (!window.addEventListener) {
                    window.attachEvent("onmessage", handling);
    }else{ // > ie8
                    window.addEventListener('message', handling, false);
    }
    

    【讨论】:

      【解决方案2】:

      我有类似的要求,最终使用 postMessage 将数据从孩子发送到父母。然后,为了将数据从父级发送到子级,我通过 iframe 的 src 属性在查询字符串中传递了数据。通过这样做,我可以解析查询字符串并在我的子页面中检索数据。

      【讨论】:

        【解决方案3】:

        从没用过那个插件,不能说它有什么问题,但是,或者你可以使用 HTML 5 postMessage。

        既然要向 iframe 发送数据,请在其上注册一个事件监听器:

        window.addEventListener('message', receiver, false);
        
        function receiver(e) {
           if (e.origin == '*') {
             return;
           } else {
             console.log(e.data);
           }
        }
        

        请务必根据您的受信任域检查来源以防止损坏,而不是接受所有的“*”。

        现在可以打电话了

        message = "data";
        iframe = document.getElementById('iframe');  
        iframe.contentWindow.postMessage(message, '*');    
        

        同样,您应该将“*”更改为目标域。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-09-04
          • 1970-01-01
          • 2014-07-01
          • 2011-08-29
          • 1970-01-01
          • 2012-07-06
          • 2011-11-23
          相关资源
          最近更新 更多