Rya*_*P13 10 iframe jquery postmessage jquery-plugins cross-domain
我正在尝试使用以下插件在子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 = $('<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
);
});
Run Code Online (Sandbox Code Playgroud)
孩子的代码如下:
$(function () {
var parentURL = decodeURIComponent(document.location.hash.replace(/^#/, ''));
$.receiveMessage(
function (e) {
alert(e.data);
},
parentURL
);
});
Run Code Online (Sandbox Code Playgroud)
我真的不明白为什么这不起作用,我迫切需要帮助!
小智 8
从来没有使用过该插件,无法真正说明它有什么问题,但是,您可以使用HTML 5 postMessage.
由于您要将数据发送到iframe,请在其上注册事件侦听器:
window.addEventListener('message', receiver, false);
function receiver(e) {
if (e.origin == '*') {
return;
} else {
console.log(e.data);
}
}
Run Code Online (Sandbox Code Playgroud)
务必检查您的可信域名的来源以防止损坏,而不是"*",它将接受所有.
现在你可以打电话了
message = "data";
iframe = document.getElementById('iframe');
iframe.contentWindow.postMessage(message, '*');
Run Code Online (Sandbox Code Playgroud)
同样,您应该使用目标域更改"*".
| 归档时间: |
|
| 查看次数: |
16776 次 |
| 最近记录: |