Stack OverflowFrame Buster Buster ... buster code needed
[+383] [19] Jeff Atwood
[2009-06-06 04:29:58]
[ javascript html iframe framebusting ]
[ ]

Let's say you don't want other sites to "frame" your site in an <iframe>:

<iframe src=""></iframe>

So you insert anti-framing, frame busting JavaScript into all your pages:

/* break us out of any containing iframes */
if (top != self) { top.location.replace(self.location.href); }

Excellent! Now you "bust" or break out of any containing iframe automatically. Except for one small problem.

As it turns out, your frame-busting code can be busted, as shown here [1]:

<script type="text/javascript">
    var prevent_bust = 0  
    window.onbeforeunload = function() { prevent_bust++ }  
    setInterval(function() {  
      if (prevent_bust > 0) {  
        prevent_bust -= 2  = ''  
    }, 1)  

This code does the following:

My question is -- and this is more of a JavaScript puzzle than an actual problem -- how can you defeat the frame-busting buster?

I had a few thoughts, but nothing worked in my testing:

I'm not much of a JavaScript programmer, so here's my challenge to you: hey buster, can you bust the frame-busting buster?

I don't have the means to test this at the moment, but it seems like the only way to block the very fast timer in the top page is to actively block the single javascript thread the browser has with an infinite loop. What I don't know is if the brower will be able to reload the top page while this is going on. top.location.replace(self.location.href); while(true) { } - Steve Reed
(6) I'm not sure the frame-buster-buster actually works...when I try to test it (redirecting to a handler I set up to return a 204), it prevents me from navigating anywhere outside the page--including typing stuff in the address bar! I have to close down the browser tab and open a new one in order to get anywhere. So in other words, I'm not sure this needs a solution, because the frame-buster-buster wanting to be busted is...busted to start with. :) (Either that or I screwed up my test, which could never happen...) ;) - Matt Winckler
(16) Matt, the frame-buster-buster code posted above definitely works. A.. uh.. friend.. of mine.. told me .. about it. Or something. :) - Jeff Atwood
... like using <body onbeforeunload="prevent_bust++"> instead of window.onbeforeunload or something like that ;] - Daniel LeCheminant
(2) well, I say to that .. top.document.body.onbeforeunload = null; :) - Jeff Atwood
(10) Jeff, are you testing with both windows on the same domain? It looks like you are because if you weren't then security restrictions would prevent you from modifying 'onBeforeUnload' - James
(29) On a side note: When posting examples, please use domains like as specified in RFC 2606 - Christoph
(1) @Matt Winckler - I agree. The buster-buster code seems very unreliable. Testing on Firefox 2 and 3, I got the same behaviour as you. In IE6,7,8, Safari 3, Opera 9.6, Chrome 2 it had no effect. - Alohci
@Steve Reed - while(true) just freezes the page, but using that idea, adding a short pause there works. By the time the interval code gets access to the thread, it's too late, and the contained page has busted out. - Alohci
I just updated my answer, please give it a try. - Josh Stodola
(1) Just out of curiosity, why would you want to do this? This sounds like it was invented by the people who wanted to stop everyone from right clicking on their page... - Zifre
(2) For those who don't get the reference. NSFW profanity - ahawker
If you want to test your buster buster buster, I made a page that frames any given URL. - Ivo Danihelka
(3) Regarding the general theme of counter-counter-countermeasures: - Joey
This guy has a question about your frame buster:… . Jeff or someone should help out this guy. - rook
Jeff, stackoverflow's frame-buster-buster-buster isn't working in Chrome 10.0.634.0 dev on Windows XP SP3. After clicking "OK" the page is blank (all white) and the iframe src is reported as The src of the iframe is set dynamically. - David Murdoch
(1) @david we don't support beta browsers.. period. - Jeff Atwood
(1) psh, this isn't a beta! Its cutting edge! haha. I just figured you'd like to know as the frame-bustin` will probably not work in a couple weeks/months when the stable channel catches up. - David Murdoch
(2) Related X-Frame-Options Mozilla spec browser support to avoid clickjacking etc. - LamonteCristo
Matt, for what it's worth, if using JQuery, you can re-enable all the links on your page after implementing the framebuster-buster with something like $("a").click(function() { prevent_bust--; }); at the bottom of the page - Chase
(1) @MattWinckler, I replicated your problem of not being able to click on anything. What I did was clear the interval after the first "onbeforeunload" to kick in. Since the frame will be the very first one to trigger that, succeeding events (such as link click) won't be blocked anymore. Code: var prevent_bust = 0 window.onbeforeunload = function() { prevent_bust++ } var interval = setInterval(function() { if (prevent_bust > 0) { prevent_bust -= 2; = ''; clearInterval(interval); } }, 1); - Ardee Aram
(1) A couple iterations later, and we'll be seeing a frame buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster buster - geoff
Does the above frame busting..buster code work today in modern browsers? It doesn't appear to work for me against: <script>if(top != self) top.location.href = location.href;</script> Also, where do we find a server that returns 204? - Bryce
[+194] [2010-03-19 18:54:06] EricLaw

FWIW, most current browsers support [1] the X-Frame-Options: deny [2] directive, which works even when script is disabled.


Firefox (3.6.9)



(6) excellent, supporting this in the browser .exe is the way to go without a doubt. When you say "most browsers", which ones specifically? I can't find good sources for anything but IE8. - Jeff Atwood
(2) Here's a test page: Chrome supports. Opera 10.50 supports. Firefox 3.6.2 does NOT yet support. Safari 4.0.3 supports. - EricLaw
(1) Firefox 3.6.9 will support it natively (… ) and any Firefox install with NoScript has had it since the beginning of 2009 ( ) - ssokolow
@JeffAtwood The latest versions of Chrome, FF, IE, Opera, Safari all support it. - Pacerier
(4) The should be the new accepted answer. - Alan
(3) It's best to combine this with the javascript framebuster. - Jesse Weigert
(1) Or combine this with the December '12 answer on this page: - LamonteCristo
@JesseWeigert why? - user1382306
X-Frame-Options are HTTP Headers not HTML Headers so it makes sense they work even with no-script on. - Pogrindis
@Pogrindis: ssokolow's point was that, prior to the introduction of native support in Firefox 3.6.9, you could get support for X-Frame-Options by having the NoScript addon installed. - EricLaw
@EricLaw i missed that! Fair enough! - Pogrindis
[+135] [2009-06-18 13:21:16] Hugoware [ACCEPTED]

I'm not sure if this is viable or not - but if you can't break the frame, why not just display a warning. For example, If your page isn't the "top page" create a setInterval method that tries to break the frame. If after 3 or 4 tries your page still isn't the top page - create a div element that covers the whole page (modal box) with a message and a link like...

You are viewing this page in a unauthorized frame window - (Blah blah... potential security issue)

click this link to fix this problem

Not the best, but I don't see any way they could script their way out of that.

(1) I have tried this and this works. Another piece that I like about this solution is that it brings to light to the user what kind of site he/she was on before going to your content. Sample Code: if (parent.frames.length > 0) { top.location.replace(document.location); setTimeout(function() { if (parent.frames.length > 0) { document.location = "";; } }, 10); } - pope
Not only is this a good way of avoiding abuse, it's pretty friendly to sites who may want to iframe your site just to take a peek at it, though not to allow use of it. Ideally, I think a screenshot of the site's homepage should be used, with some explanation of why it can't be used in the iframe overlaid on top. - wheresrhys
(28) This is how Facebook does it. - shamittomar
(2) but maybe this could be exploited if the busting site in turn will create a false anti anti anti ... (dunno how much anti we are up to now) lighbox div for itself presenting a phishing link or whatever ... tbc - HerrSerker
(5) Another idea would be to just wipeout the page completely with something like document.write(""); (after you have established that it is being framed - gabeio
Keep in mind that a proxy can always be used to defeat any frame-buster. This is used by sites like Optimizely in their WYSIWYG editors. You'll see that instead of <iframe src=""> they use <iframe src=""> and this yields the same visual result and (AFAIK) cannot be defeated as it's indistinguishable from a legitimate visitor. - Cooper Maruyama
[+30] [2009-06-06 04:55:18] Jani Hartikainen

Came up with this, and it seems to work at least in Firefox and the Opera browser.

if(top != self) {
 top.onbeforeunload = function() {};

(2) both Jani and Jeff's solution (once edited) are correct and work equivalently; giving Jani the accept because his solution worked right without any editing - Jeff Atwood
(27) This will only work if the two windows are of the same domain; a rare occurrence when you want to escape from a frame. - James
If there are nested frames involved, you'll have to walk the frame chain and remove all onbeforeunload handlers, not just the one on top! - Christoph
(12) important clarification: this worked for me because the iframe src= was being set dynamically, and thus the cross-domain policy was NOT in effect. J-P is absolutely right, in a static src= this wouldn't work. - Jeff Atwood
(5) ok now can someone come up with a frame buster buster buster buster? - Epaga
Jeff, are you trying to say that setting the SRC to a different domain programmatically bypasses the cross-domain policy? If so, that seems like a ridiculous bug that you certainly should not rely on. - Josh Stodola
Additionally, if that is true, all the evil site has to do to counteract this is set the SRC on the server-side instead...? - Josh Stodola
@Epaga I did. - uınbɐɥs
[+26] [2012-12-04 17:26:26] Dungeon Hunter

We have used the following approach in one of our websites from

 body { 
 display : none   
if(self == top) {
document.getElementsByTagName("body")[0].style.display = 'block';
top.location = self.location;

(3) Bingo! Not sure why this isn't upvoted more since it is the best answer(next to the X-Frame-Options answer, but it's best to combine both) - Jesse Weigert
This answer or mine should be selected :) - user1646111
I like your idea of using both this and the X-Frame-Options:deny answer. - Max West
This requires JS, which is a pretty big burden IMHO. - Navin
+1 - This is the best answer when X-FRAME-OPTIONS can't be used. (For example, when you need to conditionally allow or deny depending on referrer.) - Jay Sullivan
[+18] [2009-06-18 14:40:02] Josh Stodola

After pondering this for a little while, I believe this will show them who's boss...

if(top != self) {, '_top');

Using _top as the target parameter for will launch it in the same window.

I wonder how this will work on mobile devices. - LamonteCristo
[+17] [2013-05-16 20:53:18] user1646111

Considering current HTML5 standard that introduced sandbox for iframe, all frame busting codes that provided in this page can be disabled when attacker uses sandbox because it restricts the iframe from following:

allow-forms: Allow form submissions.
allow-popups: Allow opening popup windows.
allow-pointer-lock: Allow access to pointer movement and pointer lock.
allow-same-origin: Allow access to DOM objects when the iframe loaded form same origin
allow-scripts: Allow executing scripts inside iframe
allow-top-navigation: Allow navigation to top level window

Please see:

Now, consider attacker used the following code to host your site in iframe:

<iframe src="URI" sandbox></iframe>

Then, all JavaScript frame busting code will fail.

After checking all frame busing code, only this defense works in all cases:

<style id="antiClickjack">body{display:none !important;}</style>
<script type="text/javascript">
   if (self === top) {
       var antiClickjack = document.getElementById("antiClickjack");
   } else {
       top.location = self.location;

that originally proposed by Gustav Rydstedt, Elie Bursztein, Dan Boneh, and Collin Jackson (2010) [1]


Thank you, sandbox works - Aziz
[+6] [2009-06-19 15:23:24] Giorgio Maone
if (top != self) {
  location.replace("about:blank"); // want me framed? no way!

Does this work? Has it been tested? - thomasrutter
[+5] [2009-06-12 01:44:09] Mike

Ok, so we know that were in a frame. So we location.href to another special page with the path as a GET variable. We now explain to the user what is going on and provide a link with a target="_TOP" option. It's simple and would probably work (haven't tested it), but it requires some user interaction. Maybe you could point out the offending site to the user and make a hall of shame of click jackers to your site somewhere.. Just an idea, but it night work..

[+5] [2009-06-19 01:47:38] Johan Stuyts

All the proposed solutions directly force a change in the location of the top window. What if a user wants the frame to be there? For example the top frame in the image results of search engines.

I wrote a prototype where by default all inputs (links, forms and input elements) are disabled and/or do nothing when activated.

If a containing frame is detected, the inputs are left disabled and a warning message is shown at the top of the page. The warning message contains a link that will open a safe version of the page in a new window. This prevents the page from being used for clickjacking, while still allowing the user to view the contents in other situations.

If no containing frame is detected, the inputs are enabled.

Here is the code. You need to set the standard HTML attributes to safe values and add additonal attributes that contain the actual values. It probably is incomplete and for full safety additional attributes (I am thinking about event handlers) will probably have to be treated in the same way:

      function replaceAttributeValuesWithActualOnes( array, attributeName, actualValueAttributeName, additionalProcessor ) {
        for ( var elementIndex = 0; elementIndex < array.length; elementIndex += 1 ) {
          var element = array[ elementIndex ];
          var actualValue = element.getAttribute( actualValueAttributeName );
          if ( actualValue != null ) {
            element[ attributeName ] = actualValue;

          if ( additionalProcessor != null ) {
            additionalProcessor( element );

      function detectFraming() {
        if ( top != self ) {
          document.getElementById( "framingWarning" ).style.display = "block";
        } else {
          replaceAttributeValuesWithActualOnes( document.links, "href", "acme:href" );

          replaceAttributeValuesWithActualOnes( document.forms, "action", "acme:action", function ( form ) {
            replaceAttributeValuesWithActualOnes( form.elements, "disabled", "acme:disabled" );
      // -->
  <body onload="detectFraming()">
    <div id="framingWarning" style="display: none; border-style: solid; border-width: 4px; border-color: #F00; padding: 6px; background-color: #FFF; color: #F00;">
        <b>SECURITY WARNING</b>: Acme App is displayed inside another page.
        To make sure your data is safe this page has been disabled.<br>
        <a href="framing-detection.html" target="_blank" style="color: #090">Continue working safely in a new tab/window</a>
      Content. <a href="#" acme:href="javascript:window.alert( 'Action performed' );">Do something</a>
    <form name="acmeForm" action="#" acme:action="real-action.html">
      <p>Name: <input type="text" name="name" value="" disabled="disabled" acme:disabled=""></p>
      <p><input type="submit" name="save" value="Save" disabled="disabled" acme:disabled=""></p>

The problem with this is the frame-maker could use position:absolute to place active button on top of your inactive buttons and the user will just see your webpage and think they are clicking YOUR buttons. - jmucchiello
The warning message would still be shown, but of course it is easy to cover the link to the safe page as you suggest. But why go through all the trouble of framing my page to get people to click on a familiar button if you can simply copy the page and achieve the same effect? The code above mainly prevents clickjacking. If you show my page invisibly above another page it isn't possible to invoke actions on my site. - Johan Stuyts
If this is placed in an IE8 restricted zone frame or Chrome sandbox frame the Javascript will never run. I wonder what modifications are needed in those cases - LamonteCristo
[+5] [2012-08-15 15:38:21] DaveRandom

I'm going to be brave and throw my hat into the ring on this one (ancient as it is), see how many downvotes I can collect.

Here is my attempt, which does seem to work everywhere I have tested it (Chrome20, IE8 and FF14):

(function() {
    if (top == self) {

    setInterval(function() {
        setTimeout(function() {
            var xhr = new XMLHttpRequest();
        }, 0);
    }, 1);

I placed this code in the <head> and called it from the end of the <body> to ensure my page is rendered before it starts arguing with the malicious code, don't know if this is the best approach, YMMV.

How does it work?

...I hear you ask - well the honest answer is, I don't really know. It took a lot of fudging about to make it work everywhere I was testing, and the exact effect that it has varies slightly depending on where you run it.

Here is the thinking behind it:

  • Set a function to run at the lowest possible interval. The basic concept behind any of the realistic solutions I have seen is to fill up the scheduler with more events than the frame buster-buster has.
  • Every time the function fires, try and change the location of the top frame. Fairly obvious requirement.
  • Also schedule a function to run immediately which will take a long time to complete (thereby blocking the frame buster-buster from interfering with the location change). I chose a synchronous XMLHttpRequest because it's the only mechanism I can think of that doesn't require (or at least ask for) user interaction and doesn't chew up the user's CPU time.

For my http://mysite.tld/page-that-takes-a-while-to-load (the target of the XHR) I used a PHP script that looks like this:

<?php sleep(5);

What happens?

  • Chrome and Firefox wait the 5 seconds while the XHR completes, then successfully redirect to the framed page's URL.
  • IE redirects pretty much immediately

Can't you avoid the wait time in Chrome and Firefox?

Apparently not. At first I pointed the XHR to a URL that would return a 404 - this didn't work in Firefox. Then I tried the sleep(5); approach that I eventually landed on for this answer, then I started playing around with the sleep length in various ways. I could find no real pattern to the behaviour, but I did find that if it is too short, specifically Firefox will not play ball (Chrome and IE seem to be fairly well behaved). I don't know what the definition of "too short" is in real terms, but 5 seconds seems to work every time.

If any passing Javascript ninjas want to explain a little better what's going on, why this is (probably) wrong, unreliable, the worst code they've ever seen etc I'll happily listen.

[+5] [2015-07-08 09:01:01] SilverlightFox

As of 2015, you should use CSP2's frame-ancestors [1] directive for this. This is implemented via an HTTP response header.


Content-Security-Policy: frame-ancestors 'none'

Of course, not many browsers support CSP2 yet so it is wise to include the old X-Frame-Options [2] header:

X-Frame-Options: DENY

I would advise to include both anyway, otherwise your site would continue to be vulnerable to Clickjacking [3] attacks in old browsers, and of course you would get undesirable framing even without malicious intent. Most browsers do update automatically these days, however you still tend to get corporate users being stuck on old versions of Internet Explorer for legacy application compatibility reasons.


[+4] [2009-06-06 04:40:24] RedFilter

Well, you can modify the value of the counter, but that is obviously a brittle solution. You can load your content via AJAX after you have determined the site is not within a frame - also not a great solution, but it hopefully avoids firing the on beforeunload event (I am assuming).

Edit: Another idea. If you detect you are in a frame, ask the user to disable javascript, before clicking on a link that takes you to the desired URL (passing a querystring that lets your page know to tell the user that they can re-enable javascript once they are there).

Edit 2: Go nuclear - if you detect you are in a frame, just delete your document body content and print some nasty message.

Edit 3: Can you enumerate the top document and set all functions to null (even anonymous ones)?

Outlook (formerly Hotmail) 'goes nuclear' if it can't get out of a frame - it puts the the entire content of the <body> inside a <plaintext> tag set to display: none. It's quite effective. - uınbɐɥs
[+3] [2009-06-06 04:48:32] Jeff Meatball Yang

I think you were almost there. Have you tried:

window.parent.onbeforeunload = null;

or, alternatively:

window.parent.prevent_bust = 0;

Note: I didn't actually test this.

(1) I edited your code sample (the test for parent seems to fail) but the edited version DOES appear to work! - Jeff Atwood
(1) Cool. It's always tricky to answer with untested code - I do it to at least get the idea across - and let the poor asker debug. :) - Jeff Meatball Yang
(12) Won't work if parent is on a different domain, which is likely the case! - Josh Stodola
[+3] [2009-07-22 09:17:09] Marius

If you add an alert right after the buster code, then the alert will stall the javascript thread, and it will let the page load. This is what StackOverflow does, and it busts out of my iframes, even when I use the frame busting buster. It also worked with my simple test page. This has only been tested in Firefox 3.5 and IE7 on windows.


<script type="text/javascript">
if (top != self){
  alert("for security reasons bla bla bla");

[+2] [2009-06-06 09:20:33] Christoph

What about calling the buster repeatedly as well? This'll create a race condition, but one may hope that the buster comes out on top:

(function() {
    if(top !== self) {
        top.location.href = self.location.href;
        setTimeout(arguments.callee, 0);

[+2] [2010-02-21 08:57:59] Robin Nixon

If you look at the values returned by setInterval() they are usually single digits, so you can usually disable all such interrupts with a single line of code:

for (var j = 0 ; j < 256 ; ++j) clearInterval(j)

[+2] [2011-02-20 14:42:48] Phcityonweb

I might just have just gotten a way to bust the frame buster buster javascript. Using the getElementsByName in my javascript function, i've set a loop between the frame buster and the actual frame buster buster script. check this post out.

[0] [2009-12-23 15:40:15] cwallenpoole

setInterval and setTimeout create an automatically incrementing interval. Each time setTimeout or setInterval is called, this number goes up by one, so that if you call setTimeout, you'll get the current, highest value.

   var currentInterval = 10000;
   currentInterval += setTimeout( gotoHREF, 100 );
   for( var i = 0; i < currentInterval; i++ ) top.clearInterval( i );
   // Include setTimeout to avoid recursive functions.
   for( i = 0; i < currentInterval; i++ )     top.clearTimeout( i );

   function gotoHREF(){
           top.location.href = "";

Since it is almost unheard of for there to be 10000 simultaneous setIntervals and setTimeouts working, and since setTimeout returns "last interval or timeout created + 1", and since top.clearInterval is still accessible, this will defeat the black-hat attacks to frame websites which are described above.

[0] [2013-12-18 19:14:53] B.F.

Use htaccess to avoid high-jacking frameset, iframe and any content like images.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://www\.yoursite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule ^(.*)$ /copyrights.html [L]

This will show a copyright page instead of the expected.

This relies on the referrer which is a) not always set (due to browser settings or extensions or simply because the referring page is using HTTPS without using <meta name="referrer" …/> and b) also set when clicking on links, so you also disallow links to your page and break the web. - Martin