检查我的网页是否嵌入在iframe中

时间:2011-05-02 15:59:32

标签: php javascript jquery iframe

我想测试我的页面(php)是否嵌入在iframe中,以便实现不同的行为。知道如何测试这个。如果有帮助我也会使用jQuery。

添加: 我特别感兴趣的是,如果有一种方法可以在服务器上测试它,而不是在客户端使用Javascript

4 个答案:

答案 0 :(得分:13)

您可以使用JavaScript,我认为以下内容应该有效:

if (top != self) {
    // you're in an iframe, or similar.
}

Link to original, meyerweb, article

<小时/> 关于问题更新的已编辑

  

添加:我特别感兴趣的是,如果有一种方法可以在服务器上测试,而不是在客户端使用Javascript进行测试

这不能在服务器端“检查”,但是,可以使用X-Frame-Options header,有两种选择:

  1. DENY:阻止资源被绑定到任何地方(假设浏览器支持X-Frame-Options标头),或者
  2. SAMEORIGIN:它允许仅使用来自同一域的网页来构建资源,就像JavaScript的同源策略一样。
  3. 要使用此功能,您需要配置服务器以发送相关标头;虽然在不知道你正在运行什么服务器的情况下无法给出具体的建议;虽然Mozilla Developer Center上的链接文章确实显示了Apache选项。

答案 1 :(得分:4)

也许:

var isInIFrame = (window.location != window.parent.location) ? true : false;

答案 2 :(得分:3)

我不知道是否有特定的JQueryway,但你可以简单地使用vanilla javascript;

if (top != self)
  alert("framed!")

答案 3 :(得分:0)

<script language="JavaScript" type="text/javascript">
function InFrame()
{

  if (top.location != location) {
  //Do whatever you need- your site is in an iframe.

  //This will redirect to your site if you need to
  //top.location.href = document.location.href ;
  //
  }
}
</script>
相关问题