Friday, 28 December 2012

Automatically break out of an iframe




Placing the following JavaScript code at the in the head of all pages on your site will ensure that if any other site iframes a page on your website, that your page will break out of the iframe and just display your page in the users browser.

<script type="text/javascript">
  if (top.location.href != self.location.href)
     top.location.href = self.location.href;
</script>

actually iframe stands for inline frame. An iframe is a floating frame that can be inserted anywhere within a web page. Here is example of iframe html tag:

<iframe src="source.html" width="200" height="200" ></iframe>



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

<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>


Share:

No comments:

Post a Comment