发布到iframe目标:无法从iframe获得响应

Post to iframe target: cannot get response from iframe

本文关键字:iframe 响应 目标      更新时间:2023-09-26

我有一个小书签。点击时(在任何页面上):

  1. 它从mypage.com插入一个带有src的脚本元素。这个src是下载的
  2. 然后src:
    • 插入iframe(DOM)
    • 插入表单(DOM)。表单以iframe为目标
    • 将数据添加到表单并提交到mypage.com
  3. mypage.com发回响应:<div id = "msg">Message back</div>
  4. 这个响应div被插入到iframe中。(在Chrome元素选项卡中验证)
  5. 现在我想提醒返回的消息"返回消息"。它不起作用

创建iframe时,我设置了它的onload事件:

var i = document.createElement('iframe');
i.setAttribute('id', 'frame-id');
i.setAttribute('onload', 'iframeFormSubmitted();');

然后我有了功能:

function iframeFormSubmitted(){
    // in try-catch, alerting error
    var iframe = document.getElementById("frame-id");
    var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
    var msg = iframeDocument.getElementById("msg").innerHTML;
    alert(msg);

}

这最终被调用了两次(我想是第一次,因为我也将表单写入iframe)。错误为:

cannot read property innerHTMl of null
cannot call method getElementById of undefined

编辑:contentDocument未定义。我认为这是一个跨域的问题:一个有内容的iFrame怎么可能有一个未定义的contentDocument对象?

在父文档(iframe所在的文档)中创建一个function,例如,父文档中的函数done,如下所示

function done(message)
{
    // do whatever you want to do with message
    alert(message);
}

从服务器(mypage.com)向iframe发送以下代码作为响应

// Call the "done" function from the iframe (the last line on the server)
echo "<script type='text/javascript'>parent.done('This is my message')</script>";

它会起作用的,我已经在我的一个项目中应用了这个该死的东西,并且工作完美。

下面给出了我的工作计划中的一些HTML片段

<form action="someAction" method="post" id="imageform" name="imageform" target="img_submit" enctype="multipart/form-data">
    <input style="display:none" type="file" name="imgfile" id="imgfile" />
    <input style="display:none" type="submit" name="subimg" value="Submit" />
</form>

这是隐藏的iframe

 <iframe style="display:none" id="img_submit" name="img_submit"></iframe>`

这是我在parent文档中的done函数(与iframe所在的文件相同)

function done(lnk)
{
    // this is being used for afile upload (ajax simulation/fake)
    loading('hide');
    document.imageform.reset();
}