Frame Busting

Safari does not support my script.

This page explains the difficulties with frame busting: that is, preventing that your page is caught in someone else's frameset.

This is a very difficult case since it touches on security. In principle browsers don't allow you to read out information from other frames if these frames come from a different server.

Readers suggested using a try/catch statement. Try reading out top.location.href, if it doesn't work redirect because you've surely been busted. Excellent idea, but old browsers don't support try/catch, and since this script can work in old browsers it should work in old browsers.

The basic idea is

if (your site is in someone else's frameset)
	top frame location = your frameset/homepage

So you have to find out if your site is framed, and if it is you should change the top frame location. Finding out if you're framed is easy, but changing the top frame location is not allowed in Safari, even though all other browsers support it.

Finding out if you're framed

You should find out if you're framed in the top frame of your site, or, if you don't use frames at all, in all pages on your site. The idea is very simple: find out if the top property, which refers to the topmost frame, is the same as self, which always is the current frame your script runs in.

I myself run the script in my frameset and use the variable quirksMode:

var quirksMode = (top == self);

If quirksMode is true your script is currently running in the top frame, which means you're not framed.

If quirksMode is false something is wrong: for some reason the script is not running in the top frame and appropriate action should be taken.

Busting frames

I do

if (!quirksMode) top.location.href = '/index.html';

If the top frame is not the frame I run this script in, refresh the top frame to my index page. Unfortunately Safari turns out not to allow this.


In general you may not read out or change any information in a page that does not come from your server. The reason is simple: if you could, you could spy on your users, for instance checking which other sites they're currently viewing.

Most browsers, however, make an exception for setting (though not reading) top.location.href. I feel this is for the express purpose of frame busting.

Browser notes

Unfortunately, in Explorer 5.5 and up on Windows, it is possible to read out interesting stuff from and even execute JavaScripts in a frame coming from another server. This bad bug is a gaping security hole, not least because the scripting is so simple.

In earlier Mozilla versions you may not set top.location.href, though you may set top.location. Very odd, and I can't explain the reasoning behind this decision. Fortunately 1.4 is normal in this respect.