【问题标题】:How to understand if page is loaded as iframe (external site) using javascript?如何了解页面是否使用 javascript 作为 iframe(外部站点)加载?
【发布时间】:2010-11-14 21:32:24
【问题描述】:

我正在尝试寻找一个可靠的解决方案来确定我的页面是否使用 javascript 在外部网站的 iframe 中加载。

如果 iframe src 位于同一个域,这很容易:您可以使用 if (window.frameElement) 或 if (window.location !== window.parent.location) 但如果 iframe src 不在同一个域上现代浏览器在访问父级时抛出异常,甚至将其与 null 进行比较。

我完全迷路了。

【问题讨论】:

    标签: javascript iframe cross-domain


    【解决方案1】:

    您可能对编码恐怖条目感兴趣:We Done Been Framed。提供有关此主题的有趣技术讨论,包括解决方案和框架破坏。

    【讨论】:

    • 好文章。 OP可能想尝试的那篇文章的代码是: if (parent.frames.length > 0) { top.location.replace(document.location);虽然这篇文章的重点是不可能 100% 从 JavaScript 中破坏框架,但您能做的最好的事情就是通知用户来自服务器端代码的框架。
    • 所以......你所说的是我的回答比提问者提供的信息更多;)
    【解决方案2】:

    您可以将验证 (window.location !== window.parent.location / window.frameElement) 包装在 try-catch 语句中,您可以使用它来自己处理异常。

    【讨论】:

    • 它不起作用——至少在 Firefox 3.6.12 中是这样。代码不会抛出异常。
    【解决方案3】:

    你为什么不试试下面的函数

    var 元素 = window.parent.document if (element) return "在父窗口中" else "不在父窗口中";

    【讨论】:

      猜你喜欢
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 2015-05-16
      • 2013-06-10
      • 2014-01-06
      • 2011-01-13
      • 2014-04-22
      相关资源
      最近更新 更多