5

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

millebii
  • 1,277
  • 2
  • 17
  • 27
  • possible duplicate of [Detect iFrame embedding in Javascript](http://stackoverflow.com/questions/925039/detect-iframe-embedding-in-javascript) – Marc B May 02 '11 at 16:02
  • possible duplicate of [How to understand if page is loaded as iframe (external site) using javascript?](http://stackoverflow.com/questions/4179795/how-to-understand-if-page-is-loaded-as-iframe-external-site-using-javascript) – Felix Kling May 02 '11 at 16:02
  • not real duplicates, because I'd like to test this on server preferably! – millebii May 02 '11 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 http://stackoverflow.com/questions/2896623/how-to-prevent-my-site-page-to-be-loaded-via-3rd-party-site-frame-of-iframe – Felix Kling May 02 '11 at 16:19
  • @Felix because it wasn't very clear in my mind. – millebii May 02 '11 at 16:22

4 Answers4

13

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:

  1. DENY: prevents the resource being framed anywhere (assuming the browser supports the X-Frame-Options header, anyway), or
  2. SAMEORIGIN: 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.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
4

maybe:

var isInIFrame = (window.location != window.parent.location) ? true : false;
alexl
  • 6,841
  • 3
  • 24
  • 29
3

I don't know if there is a specific JQueryway but in vanilla javascript you can simply;

if (top != self)
  alert("framed!")
Alex K.
  • 171,639
  • 30
  • 264
  • 288
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>
Piotr Kula
  • 9,597
  • 8
  • 59
  • 85