【问题标题】:How get iframe body after load?加载后如何获取 iframe 正文?
【发布时间】:2011-05-08 04:27:27
【问题描述】:

我需要在 iframe 加载后获取 iframe 正文

【问题讨论】:

  • 我需要你更简洁。
  • 如果文档位于另一个域中,您将无法从该 iframe 中获取任何内容。

标签: jquery iframe


【解决方案1】:

document.getElementById('frame').contentDocument.body 会在纯 JavaScript 中给你它,假设 iframe 的 ID 是frame。在 jQuery 中,这将是 $('#frame').contents().find('body')

请注意,由于同源策略,这仅在 iframe 和周围页面的 URL 具有完全相同的主机名和端口号时才有效。

编辑:您评论说您在尝试此代码时收到“访问被拒绝”错误。同源政策就是为什么会发生这种情况。优秀的浏览器安全手册有information about this。仔细阅读该网页会发现有一些突破的方法,尽管出于安全和隐私原因,除非您控制封闭的网站,否则这是不可能的。

【讨论】:

  • iframe src 它位于另一台服务器中,并且 (iFrame.contentDocument) 返回错误“Permission denied”或“Access denied”
【解决方案2】:

由于security reasons,如果它位于不同的域中,则无法使用 javascript 获取 iframe 内容。改为查看JSONP

【讨论】:

    【解决方案3】:

    经过大量搜索后,jQuery 解决方案实际上非常简单,所以当我通过各种代码和函数试图找到一些东西时,我想我会为其他人节省 30 分钟的头痛。

    您实际上可以使用 parent. 访问父文档中的函数和变量,因此您实际上只需要向 iframe onload 添加一个事件侦听器即可运行 parent.function();

    请记住,iframe 没有加载父级拥有的 javascript 文件(即没有 jQuery,没有 momentJS 等),因此在我的情况下,在父级上运行该函数是一个很好的方法。

    <script>
    function afterLoading(){
        $('#messageLog').html('TIMESTAMP ---'+'>'+$('#displayWindow').contents().find("body").html()+'\n'+$('#messageLog').html());
    }
    $('#displayWindow').on('load', function(){
        parent.afterLoading();
    });
    //below this is the complete code, the above 2 functions is how it works
    setInterval("printQueue()",10000);
    function printQueue(){
        $('#displayWindow').attr("src","");
        $('#displayWindow').attr("src","http://127.0.0.1/test.php");
    }
    </script>
    <div class="col-xl-4">
        <textarea id="messageLog" style="width:100%;height:100%;"></textarea>
    </div>
    <div class="col-xl-4">
        <iframe id="displayWindow" style="width:100%;height:100%;"></iframe>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2012-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      相关资源
      最近更新 更多