Created
January 12, 2012 04:58
-
-
Save nathansmith/1598861 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
If you want to use iFrames on your own site, you probably want to compare this.top.location.hostname instead.
this.top.location.hostname !== this.location.hostname && (this.top.location = this.location);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I felt inspired to share, after seeing Chris' snippet over at CSS Tricks...
http://css-tricks.com/snippets/javascript/break-out-of-iframe