【问题标题】:content of dynamically created iframe is empty动态创建的 iframe 内容为空
【发布时间】:2012-05-09 03:31:42
【问题描述】:

在我的本地主机上,我使用以下 JavaScript 创建一个带有srciframe,并将其添加到文档中:

$('#preview').html('<iframe src="http://google.com/"></iframe>');

iframe 显示但不显示内容。在萤火虫中,它只是:

<iframe src="http://google.com/">
    <html>
        <head></head>
        <body></body>
    </html>
</iframe>

当我在控制台上执行 $('iframe').attr('src','http://google.com/'); 时,浏览器会加载(显示“正在等待 google.com...”),然后似乎会刷新 iframe 的内容。但同样,它是空的。

但是,如果我将其设置为本地页面,则会加载内容。

这是因为同源政策吗?我对此不太了解。我做了一些谷歌搜索,但我很困惑,因为有些网站说可以在不属于您自己的域的 src 中包含 iframe,而有些人说这是不可能的。

顺便说一句,由于我仍在本地主机上进行测试,如果我将它上传到某处的服务器,这会起作用吗? (但 iframe 的 src 仍将在不同的域中)

帮助?

【问题讨论】:

    标签: javascript jquery html iframe


    【解决方案1】:

    是的,由于同源政策,该代码被禁止。阅读here

    假设您拥有域http://www.example.com,那么当您通过 iframe 调用页面时,您可能会得到以下结果:

    Compared URL                               Outcome  Reason
    ---------------------------------------------------------------------------------------------
    http://www.example.com/dir/page.html       Success  Same protocol and host
    http://www.example.com/dir2/other.html     Success  Same protocol and host
    http://www.example.com:81/dir2/other.html  Failure  Same protocol and host but different port
    https://www.example.com/dir2/other.html    Failure  Different protocol
    http://en.example.com/dir2/other.html      Failure  Different host
    http://example.com/dir2/other.html         Failure  Different host (exact match required)
    http://v2.www.example.com/dir2/other.html  Failure  Different host (exact match required)
    

    现在,您正在调用 google.com,这是一个跨域问题。要解决此类问题,JSONP 可以帮助您。它使用&lt;script&gt; 的开放脚本策略,从跨域检索 JSON。

    【讨论】:

      【解决方案2】:

      如果您检查了浏览器的错误控制台,您会看到以下消息:

      拒绝显示文档,因为 X-Frame-Options 禁止显示。

      因此,这不是您的错误,而是 Google 的故意行为。

      X-Frame-Options 的两个选项是:

      • deny - 帧内没有渲染,并且
      • sameorigin - 如果原点不匹配则不渲染

      参考资料:

      【讨论】:

      • 非常感谢。当我试图将谷歌地图加载到 iframe 中时,第三个链接 (SO) 很有帮助。
      猜你喜欢
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 2013-01-27
      • 2010-10-24
      • 2012-05-30
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      相关资源
      最近更新 更多