gpt4 book ai didi

javascript - 如何使用postMessage跨域发送数据?

转载 作者:搜寻专家 更新时间:2023-11-01 04:37:19 24 4
gpt4 key购买 nike

我在另一个域的 iFrame 中有一个上传脚本。我正在尝试将文件上传 data 发送到嵌入了 iFrame 的页面。

我在 iFrame(上传脚本)中有以下代码:

$('#file_upload').uploadify({
//JS CODE
'onUploadSuccess' : function(file, data, response) {
data //data is what must be passed from the iFrame to the script on another site
}
});

data 是必须传递给另一个域上的以下脚本的内容:

var myframe, nestedFrame;
myFrame = $('#editorf').contents().find('body');
nestedFrame = myFrame.find('#re_contentIframe').contents().find('body');
nestedFrame.append('data'); //data should be replaced with the information from the iFrame

我确实尝试了以下代码:

iFrame 代码 - 页面 B

$('#file_upload').uploadify({
//JS CODE for UPLOADIFY
'onUploadSuccess' : function(file, data, response) {
window.postMessage('http://iframe-domain.net/uploads/' + data,'http://iframe-domain.net');
}
});

接收页面代码 - 页面 A

$(function() {
window.addEventListener('message', receiver, false);

function receiver(e){
if (e.origin == 'http://iframe-domain.net'){
var myframe, nestedFrame;
myFrame = $('#editorf').contents().find('body');
nestedFrame = myFrame.find('#re_contentIframe').contents().find('body');
nestedFrame.append(e.data);
}
}
});

这行不通。我确实收到此错误消息:

Error: Permission denied to access property 'toString'
...a);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$...

jquery.uploadify.js (line 17)

uploadify 脚本确实在文件上传时起作用,但它似乎没有将数据传递到页面。我不相信此错误是页面无法正常工作的原因。

我该怎么做?

编辑

为了更好地解释这里是一个例子:

一个人前往页面 A(主页)。在页面 A 上,该页面上嵌入了一个 iFrame。 iFrame 内部有一个 uploadify 脚本,允许用户上传文件。

一个人上传一个文件,uploadify 脚本返回文件名。示例:528050f030522.jpg。一旦 uploadify 脚本获得此信息,它应该将其发送到页面 A 的脚本,然后该脚本运行并将文件名插入页面。

最佳答案

在您的 iframe 中,您有 window.postMessage(URL,sendingOrgin),但这不是您将数据发送到另一个窗口的方式。如果我明白this page正确地,您改为使用 otherwindow.postMessage(data,receivingOrigin)

因此,首先(在您的 iframe 中)创建一个新的 iFrame,为其提供一个 onload 事件处理程序,并在该窗口加载后调用该窗口的 postMessage 方法。像这样

var iframe=document.createElement("iframe");
iframe.onload=function(){
iframe.contentWindow.postMessage(data,"http://receivingdomain.com");
}
iframe.src="http://receivingdomain.com/receivingPage.html"

编辑:另外,请注意,如果您只想单向发送信息(并且每个 iframe 一次),打开一个带有 URL http://receivingdomain 的 iframe 可能会容易得多。 com/receivingPage.html?data=... 并在接收页面上读取其自己的 window.location 以提取数据...

关于javascript - 如何使用postMessage跨域发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19898461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com