iframe跨域消息传递与jQuery postMessage插件 [英] iframe cross domain messaging with jQuery postMessage plugin
问题描述
我尝试使用以下插件在子项iframe及其父项之间进行通信:
I am trying to communicate between a child iframe and its parent using the following plugin:
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 = $('<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
);
});
我真的看不出为什么这不工作,急需帮助!
I really cannot see why this is not working and am in desperate need of help!
推荐答案
从来没有使用过这个插件,不能真正说它有什么问题,但是,或者你可以使用HTML 5 postMessage。
Never used that plugin, can't really say what's wrong with it, but, alternately you can use HTML 5 postMessage.
由于您要向iframe发送数据,请在其上注册一个事件监听器:
Since you want to send data to the iframe, register an event listener on it:
window.addEventListener('message', receiver, false);
function receiver(e) {
if (e.origin == '*') {
return;
} else {
console.log(e.data);
}
}
请务必检查您的信任网域
Be sure to check origin against your trusted domain to prevent damage, instead of "*" which will accept all.
现在您可以致电
message = "data";
iframe = document.getElementById('iframe');
iframe.contentWindow.postMessage(message, '*');
同样,您应该使用目标网域更改*。
Again, you should change "*" with the destination domain.
这篇关于iframe跨域消息传递与jQuery postMessage插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!