Framing Pages With JavaScript

Normally, when building a website, we’d not want our content to be in frames.

However, a project at work involved hosting some content externally from the parent site that was framed in the parent site.

That’s fine, nothing to difficult, but this content also provided an RSS feed and those links had to feed back into the parent page, so needed to launch the site framework around itself if it didn’t already exist.

The solution to this was to be have two JavaScript’s, one in the piece of content, and the other in the parent framework. When the content is loaded it needs to check if it’s framed, and if it’s not to load the parent framework which then needs to reload the content.

Here’s the code that goes into the content…

<script language="JavaScript" type="text/javascript">
if (self == top) {
var newurl = "http://www.myparentsite.com/?url=" + encodeURI(window.location.href);
if (document.images) {
top.location.replace(newurl);
} else {
top.location.href = newurl;
}
}
</script>

So what’s going on here? Well firstly we need to check if the content page has been launched in a frameset or not. To do this we check if self is the same as top. self is a JavaScript object that refers to the current page, and top is a JavaScript object that refers to the top of the current page, so this could be the parent page of multiple framesets. If it’s the same we know we’re at the top of the page and not in a frameset, so we need to launch the parent page architecture. To do this we work out what the URL of a parent will be and get JavaScript to tell the browser to goto to that page. If you look at the code here, you’ll see the parent site I’ve called www.myparentsite.com, but this could be anything. I append a parameter called url that is an encoded version of the current page’s URL.

When our parent page loads, it needs to see if it has a URL parameter to load in the content frame correctly. We use the following code on the parent page to achieve this.

<script language="JavaScript" type="text/javascript">
var newurl = decodeURI(location.search.slice(5));
if (newurl) {
// nothing actually :-)
} else {
newurl = "http://www.framedcontent.com/defaultcontent.html";
}
document.write('<iframe src="' + newurl + '" scrolling="no" width="492" height="680" frameborder="0" ></iframe>')
</script>

All we’re doing here is getting a whatever parameter string is passed in and treating it as a URL. If we don’t have a parameter we use a default. We then create a new iframe referring to this URL.

As you can see we make no effort to check the parameter passed in is a valid URL or even if it’s in the url parameter. This is very bad code, but serves to demonstrate the technique. In real life we’d check for the url parameter and that it is valid.