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.
Addition : I'm especially interested if there would be a method to test this on the server rather than in the client with Javascript
-
possible duplicate of Detect iFrame embedding in JavascriptMarc B– Marc B2011年05月02日 16:02:06 +00:00Commented May 2, 2011 at 16:02
-
possible duplicate of How to understand if page is loaded as iframe (external site) using javascript?Felix Kling– Felix Kling2011年05月02日 16:02:37 +00:00Commented May 2, 2011 at 16:02
-
not real duplicates, because I'd like to test this on server preferably!millebii– millebii2011年05月02日 16:17:46 +00:00Commented May 2, 2011 at 16:17
-
So why do you tag your question with JavaScript and jQuery then? It is not possible at the server side. But even then it would be a duplicate of stackoverflow.com/questions/2896623/…Felix Kling– Felix Kling2011年05月02日 16:19:29 +00:00Commented May 2, 2011 at 16:19
-
@Felix because it wasn't very clear in my mind.millebii– millebii2011年05月02日 16:22:21 +00:00Commented May 2, 2011 at 16:22
4 Answers 4
You could use JavaScript, I think something like the following should work:
if (top != self) {
// you're in an iframe, or similar.
}
Link to original, meyerweb, article.
Edited with regard to the question's update:
Addition : I'm especially interested if there would be a method to test this on the server rather than in the client with Javascript
This can't be 'checked' on the server side, but, you could use the X-Frame-Options header, there are two options:
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.
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 Center does show the Apache option.
Comments
maybe:
var isInIFrame = (window.location != window.parent.location) ? true : false;
2 Comments
? true : false for?var isInIFrame = (window.location != window.parent.location); anyway, its the samethingI don't know if there is a specific JQueryway but in vanilla javascript you can simply;
if (top != self)
alert("framed!")
Comments
<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>