javascript 检查我的页面是否嵌入在 iframe 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5859358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if my page is embedded in an iframe
提问by millebii
I would like to test if my page (php) is embedded in an iframe or not, in order to implement a different behaviour. Any idea how to test this. I'm also using jQuery if it helps.
我想测试我的页面 (php) 是否嵌入在 iframe 中,以实现不同的行为。任何想法如何测试这个。如果有帮助,我也在使用 jQuery。
Addition :I'm especially interested if there would be a method to test this on the server rather than in the client with Javascript
另外:我特别感兴趣的是是否有一种方法可以在服务器上而不是在客户端使用 Javascript 进行测试
回答by David says reinstate Monica
You could use JavaScript, I think something like the following should work:
您可以使用 JavaScript,我认为以下内容应该有效:
if (top != self) {
// you're in an iframe, or similar.
}
Link to original, meyerweb, article.
Edited编辑关于问题的更新:
Addition: I'm especially interested if there would be a method to test this on the server rather than in the client with Javascript
另外:我特别感兴趣的是是否有一种方法可以在服务器上而不是在客户端使用 Javascript 进行测试
This can't be 'checked' on the server side, but, you coulduse the X-Frame-Options
header, there are two options:
这不能在服务器端“检查”,但是,您可以使用X-Frame-Options
header,有两个选项:
DENY
: prevents the resource being framed anywhere (assuming the browser supports the X-Frame-Options header, anyway), orSAMEORIGIN
: which allows framing of the resource only by pages from the same-domain, much like JavaScript's same-origin policy.
DENY
: 防止资源在任何地方被框架化(假设浏览器支持 X-Frame-Options 标头,无论如何),或SAMEORIGIN
: 允许仅通过来自同一域的页面来构建资源,就像 JavaScript 的同源策略一样。
To use this, you'd need to configure your server to send the relevant header; though specific advice for that can't be given without knowing what server you're running; though the linked article at the Mozilla Developer Centerdoes show the Apache option.
要使用它,您需要配置您的服务器以发送相关标头;尽管在不知道您正在运行的服务器的情况下无法给出具体建议;尽管Mozilla 开发人员中心的链接文章确实显示了 Apache 选项。
回答by alexl
maybe:
或许:
var isInIFrame = (window.location != window.parent.location) ? true : false;
回答by Alex K.
I don't know if there is a specific JQueryway but in vanilla javascript you can simply;
我不知道是否有特定的 JQueryway,但是在 vanilla javascript 中,您可以简单地;
if (top != self)
alert("framed!")
回答by Piotr Kula
<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>