The Digg Bar is the most obvious (and noxious) example, but the new trend of URL shorteners coupled with a URL hijacking frame is spreading alarmingly. More and more I’m seeing this odious technique. These things break bookmarks, wreck navigation cues from the URL and are generally sleazy and rude.
And there’s how to beat them. Insert this code in the head
of your document and frames will disappear:
Best Frame-buster JavaScript
<script type="text/javascript">
//if the topmost frame is not the document calling the code
//we do some stuff to make sure we're not being hijacked
if (top != self ) {
//Add a whitelist array.
//Add any site you WANT to be able to frame your site.
//The default allows for your own site to frame the page.
//It just seemed like the way to go.
//Are there any other typical sites that need to be whitelisted?
var whitelist =[
document.location.hostname
];
var i;
var test = whitelist.length;
var safe = false;
//Then we simply test for the presence of the
//Frame's location in the whitelist array
for (i=0; i < test ; i++) {
if (document.referrer.indexOf(whitelist[i]) != -1 ) {
//if it is, it's safe
safe= true;
}
}
//if it's not, bust a move
//and kill that (hijacking) noise
if (safe=== false) {
top.location.replace(document.location);
}
}
</script>
Are there any common, beneficial services I should whitelist?
And how would this not be a violation of the same origin policy?
This code will fail (throw an exception) if the framing document is on a different domain than the framed document.
So sorry mate, not exactly the best code.. If anything you could check against location.referrer..
Ack! Thanks for pointing that out. I’d actually fixed the demo (don’t blink 🙂 ) for that very reason and forgot to update my sample code.
You should read this first, then try to “solve” the problem:
http://www.codinghorror.com/blog/archives/001277.html
Thanks Mickro. That’s interesting reading- I just lost 45 minutes following links.