【问题标题】:disable iframe embedding for other websites禁用其他网站的 iframe 嵌入
【发布时间】:2017-04-17 16:16:36
【问题描述】:

我想禁用 iframe 嵌入页面,从我的网站到其他网站 我做这个js:

<script type="text/javascript"> if(document.referrer.indexOf("mydomain.com") != -1) { window.location = "http://www.youtube.com/watch_popup?v=oHg5SJYRHA0"; } </script>

脚本有效,但我有 page01.php 和 page02.php

我想在 page01.php 源代码中为 page02.php 插入 iframe

<iframe src="page02.php"></iframe> 

当我这样做时,我被重定向到:

http://www.youtube.com/watch_popup?v=oHg5SJYRHA0

如何解决这个问题? 谢谢

【问题讨论】:

  • 更改window.location = "&lt;destination_url&gt;" 中的目标字符串?无论如何我都会在服务器端编写代码

标签: javascript iframe referer


【解决方案1】:

我建议您使用 X-Frame-Options 标头。如果您使用的是 nginx,您可以在 server 或 location 块中添加此行:

add_header X-Frame-Options "SAMEORIGIN";

当您添加此标头时,如果有人试图在框架中加载您的页面,现代浏览器将拒绝该请求。请注意,这不适用于旧版浏览器。

【讨论】:

  • 也许这是个好主意,但是在哪里添加这段代码呢?在我的 page02.php 或网站 index.php 中?或者也许在 htaccess 文件中?你能给我举个例子吗?谢谢
  • 这个 sn-p 进入 nginx 服务器配置文件。看来您正在使用 Apache。尝试将Header add X-Frame-Options "SAMEORIGIN" 添加到您的 .htaccess 文件中
  • 其实
  • 这是在 Netlify 上执行此操作的方法。 docs.netlify.com/routing/headers/…
【解决方案2】:

如果你不想把保护留给浏览器,你仍然可以使用 JS。

//Check if the page is loaded in an iframe
if(window.self != window.top) {
  //Almost all browsers will deny Cross-Origin script access, so
  //we will use a try-catch block
  try {
    if(window.parent.location.hostname.indexOf("mydomain.com") == -1) {
      window.location.href = "http://www.youtube.com/watch_popup?v=oHg5SJYRHA0";
    } else {
      //You are in an iframe but Same-Origin
    }
  } catch (ex) {
    //Congrats, you are in an iframe loaded in a stranger's site!
    window.location.href = "http://www.youtube.com/watch_popup?v=oHg5SJYRHA0";
  }
}

【讨论】:

  • 感谢您的回答,但使用此代码,我有相同的问题。没有任何改变..
【解决方案3】:

对于 PHP 网站,您可以在脚本的开头、任何输出之前写下这一行:

header( 'X-Frame-Options: DENY' );

更多关于头函数here.

【讨论】:

  • (现在我无法更新这个答案:您可以谈论在 PHP 脚本的开头删除这一行,而不是专门与 WordPress 交谈。)
【解决方案4】:

接受的答案很好,但如果您想确保没有网站可以将您的网站放入 iFrame,包括同一来源的其他网站,建议使用“X-Frame-Options DENY”。见:

https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html#x-frame-options-header-types

【讨论】:

    猜你喜欢
    • 2011-01-24
    • 2018-06-09
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    相关资源
    最近更新 更多