How to: Bust into an iFrame

12 October 2010

Yes, you read that correctly, I want to tell bust *into *an iFrame.

First the details:

The Fourum is built in a funny way because we built it so fast and wanted to make it dead simple. We currently use a PHP file for the header so people can submit their thoughts to us and it sends an e-mail with each submission (Shown below).

The content section of the Fourum uses a Tumblr Blog to display simple blog posts.

Both of these sites work independently of each other. www.thefourum.com points to the php file that has the header and loads the tumblr blog in an iFrame where it should be displayed.

"An inline frame places another HTML document in a frame. Unlike an object element, an inline frame can be the 'target' frame for links defined by other elements and it can be selected by the user agent as the focus for printing, viewing its source etc." Definition from wikipedia.

Tumblr's twitter integration actually posts links to the tumblr blog so when you click these links you are directed to a version of the Fourum that does not have a header and it a bit annoying, also some of the search results for specific fourum posts link to the tumblr blog and these also load without a header.

How its done:

In some recent work for another client I came across a way to be able to tell if the page is loaded in an iFrame or not. The following uses an if statement to determine that top window is at the same address as the document the code is in (self) and since they are the same, it is not loaded in an iFrame. Thus, it redirects the user by setting the window.location to the default address that should have been loaded. It passes along the path or whatever is after "http://thefourum.tumblr.com/" such as "/page/2/" in the GET variable "href".

<script type="text/javascript">
if (window.top === window.self) {
    window.location = 'http://thefourum.com?href=' + window.location.pathname;
}
</script>

Once this redirection is done the PHP script at http://thefourum.com loads, adds the GET variable "href" to the end of the source ("src") of the iframe. This makes sure that you stay on the same page you meant to go to instead of redirecting you to the most recent entries.

<iframe name="content" frameborder="0" style="height: 975px;" scrolling="no" src="http://thefourum.tumblr.com<?= $_GET['href'] ?>" width="100%">
    <p>Your browser does not support iframes.</p>
</iframe>

There you have it, how to bust into an iFrame. 8 lines of code and a little bit of cleverness.