动态创建的 iframe 的内容为空

content of dynamically created iframe is empty

本文关键字:iframe 创建 动态      更新时间:2023-09-26

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

$('#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仍将在不同的域中)

帮助?

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

拒绝显示文档,因为 X 帧选项禁止显示。

所以,这不是你的错误,而是谷歌的故意行动。

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

  • deny - 帧内没有渲染,以及
  • sameorigin - 如果源不匹配,则不呈现

引用:

  • X-Frame-Options响应标头,在 MDN。
  • X-Frame-Options在维基百科。
  • 克服"X帧选项禁止显示"(在堆栈溢出上)。

是的,由于同源策略,该代码被禁止。在这里阅读

假设您拥有域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可以帮助您。它使用<script>的开放脚本策略,从跨域检索JSON。