treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Break Out of iframe

Last updated on:

if (top.location!= self.location) {
   top.location = self.location.href;
}

That will generally work, but there is a small chance of failure in the case that window is overridden. Here's a couple of clever alternatives from Nathan Smith:

<script>

// Break out of an iframe, if someone shoves your site
// into one of those silly top-bar URL shortener things.
//
// Passing `this` and re-aliasing as `window` ensures
// that the window object hasn't been overwritten.
//
// Example:
//   var window = 'haha, punked!';
//
// Note: Probably unnecessary, but just for kicks.

(function(window) {
  if (window.location !== window.top.location) {
    window.top.location = window.location;
  }
})(this);

</script>
<script>

// A more cryptic one-liner, to awe & impress.
//
// No need to protect `window` since `this` is
// immutable, and at the topmost level means
// `window` anyways. Here, we compare locations
// on the left side of the "&&" and execute the
// code in parenthesis if that condition is
// true (top location isn't iframe location).
//
// Otherwise, nothing happens. It's basically an
// if statement without wrapping curly brackets.
//
// Weird, I know. But pretty cool, right? :)

this.top.location !== this.location && (this.top.location = this.location);

</script>

Reference URL

View Comments

Comments

  1. Permalink to comment#

    Is there any way to prevent it? From the parent.

  2. The Fastest
    Permalink to comment#

    please, examples of blogs using an iframe

  3. Permalink to comment#

    Unable to get this to work on word press

  4. Scott
    Permalink to comment#

    Will this result in registering two visits if I’m using Google Analytics to track it?

    If so, is there an alternate method that will allow the breakout, but not register two visits?

Leave a Comment

Use markdown or basic HTML and be nice.