使用jQuery postMessage插件的iframe跨域消息传递

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

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

我可以按照示例将一条消息从孩子发布到父母而不是其他方式,我真的需要能够以两种方式进行交流。

父代码如下:

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 = $(''); // 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 ); }); 

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

从来没有使用过该插件,无法真正说明它有什么问题,但是,您可以使用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, '*'); 

同样,您应该使用目标域更改“*”。

 1.sendPage  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); } 

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