Tuesday, December 4, 2012

Hide Content Based Upon Iframe Parent

Some web sites use iframes to display information from other web servers.  This is a practice that is generally frowned upon yet is a necessary evil sometimes.

I work on an employee intranet where we need to display content from another internal server.  The problem is that sometimes our employees access the site from off of our domain where they don't have access to the internal server.  To get around this issue I've created an extremely simple javascript snippet which can be added to the page to hide the content and display a message to the user explaining why they can't see the content.

I'm posting it here as a reference for myself and in case someone out there needs something like this!


<div id="whatever">Your content</div>

<STYLE type=text/css>
   .hidden { display: none; }
</STYLE>

<script type="text/javascript">

   function referrerCheck()
   {
      var mapReferrer = document.referrer;
      var mapDiv = document.getElementById('content');

      if(mapReferrer=="http://this is the URL calling the iframe")
      {
         mapDiv.className='unhidden';
      }else{
         mapDiv.className='hidden';
      }
   }

   referrerCheck();

</script>

How it works:
  1. All of this code goes onto the page which calls the iframe.
  2. The div at the top is where your iframe goes - what you want to hide if folks are off the domain.
  3. The style section sets the stage for what you want to happen if folks are off the domain.  In this case we want to not display the entire div.
  4. The javascript runs the referrerCheck() function which grabs the document.referrer which is the page that calls the iframe.
  5. The getElementById functions gets the div object so that its class can be manipulated.
  6. The If condition then determines whether or not the referrer is on or off domain and sets the class accordingly.

No comments:

Post a Comment