1

Say, I have a site with URL site.com . How do I know if a referrer gets my URL from an iframe, like this: <iframe src="http://site.com"></iframe> OR a referrer CLICKS (!!) this link at some site, where link is a usual a-tag: <a href="http://site.com">go to site</a> ?

I wanna tell those two apart on my server-side. Maybe, there is a way to do that via JS? Thanks in advance.

No Way
  • 183
  • 9

3 Answers3

3

It can be done in javascript, but not on the server-side directly. You can, however, pass this information to the server by redirecting in one of the two cases with a simple javascript:

if (window.self === window.top) {
  // you're not in an iframe
} else {
  // in an iframe (or other frames), act accordingly
}

Optionally, if you just want to prevent your site from being viewed in an iframe, you can do this by sending an X-Frame-Options header.

Michael Lawrie
  • 1,534
  • 11
  • 20
0

Javascript is client side only (unless you are using Node.js), so there is no way to tell on the server side whether something is being referenced from an iframe or a normal hyperlink.

What is your reason for wanting to do this? It seems as though you are going to have to find another way around your problem.

krishnakid
  • 108
  • 5
0

If you are trying to prevent your site from being displayed in an iframe, one of the best ways you can do this is with a frame-breaking script. (Note that the request/response will still occur with your webserver).

Include the following in the <head> of any document you wish not to be "framed".

<style id="antiClickjack">body{display:none !important;}</style>
<script type="text/javascript">
   if (self === top) {
       var antiClickjack = document.getElementById("antiClickjack");
       antiClickjack.parentNode.removeChild(antiClickjack);
   } else {
       top.location = self.location;
   }
</script>
OregonTrail
  • 8,594
  • 7
  • 43
  • 58
  • Here's a link to a `owasp.org` document about this approach: https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Best-for-now_Legacy_Browser_Frame_Breaking_Script – KajMagnus Dec 07 '13 at 01:54