iframe和外部网站

时间:2011-11-27 07:22:15

标签: html iframe web

所以我有这段代码:

<iframe id="theFrame" src="http://localhost" style="width:100%;" frameborder="0">
</iframe>

和iframe中加载的localhost网站就好了。

但是当我将src更改为外部网站时

<iframe id="theFrame" src="http://www.youtube.com" style="width:100%;" frameborder="0">
</iframe>

该网站未加载。

我做错了什么?我知道您可以在iframe中使用外部网站,因为Google图片搜索会这样做......

如何在iframe中使用外部网站?

4 个答案:

答案 0 :(得分:24)

外部网站之所以如:

  1. youtube.com
  2. google.com
  3. stackoverflow.com
  4. 未加载,因为他们故意利用某种 Frame Killer

    示例(使用jQuery)

    <style> html{display:none;} </style>
    <script type="text/javascript">
        $(document).ready(function () {
            if(window.self == window.top) {
                document.documentElement.style.display = 'block'; }
            else {
           window.top.location = window.self.location; }
        });
    </script>
    

    建议阅读:

答案 1 :(得分:4)

您可能遇到了我遇到的相同问题,很可能iframe被X-frame-options阻止或被Deny属性阻止。例如,如果您从外部来源访问Facebook,它将在谷歌浏览器中返回DENY响应

答案 2 :(得分:0)

如果您运行以下代码段:

<iframe src="https://www.youtube.com"></iframe>

然后查看开发工具,它将引发错误:

  

拒绝在帧中显示“ https://www.youtube.com/”,因为它将“ X-Frame-Options”设置为“ sameorigin”。

这是因为您尝试访问的网站将嵌入{通过iframeframeembedobject限制为使用{{3 }}标头。因此youtube.com可以正常加载youtube.com页面的iframe,但没有其他人可以加载。只有嵌入式网站的网站管理员才能更改该设置。

如果您要嵌入网站的管理员,则可以将宿主网站列入白名单:

X-Frame-Options: allow-from https://my-host-site.com/

这必须由您要嵌入的页面的服务器作为HTTP标头发送。它不能作为HTML meta中的head标签使用。这样浏览器就可以知道您正在嵌入的网站,也可以通过托管网站在iframe中显示页面。

答案 3 :(得分:-3)

它似乎只是一个youtube问题; src =“http://www.mozilla.org”适用于您的代码。如果您想在iframe中显示YouTube视频,他们可能会要求您在视频页面上使用“嵌入”选项?