How do I know (on the server side) if someone came to it from an iframe or directly? See inside [duplicate]

StackOverflow https://stackoverflow.com/questions/17075869

  •  31-05-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top