当前位置:Gxlcms > JavaScript > js实现防止被iframe的方法

js实现防止被iframe的方法

时间:2021-07-01 10:21:17 帮助过:15人阅读

本文实例讲述了js实现防止被iframe的方法。分享给大家供大家参考。具体如下:

方法一:

  1. <script>
  2. // Break out of an iframe, if someone shoves your site
  3. // into one of those silly top-bar URL shortener things.
  4. //
  5. // Passing `this` and re-aliasing as `window` ensures
  6. // that the window object hasn't been overwritten.
  7. //
  8. // Example:
  9. // var window = 'haha, punked!';
  10. //
  11. // Note: Probably unnecessary, but just for kicks.
  12. (function(window) {
  13. if (window.location !== window.top.location) {
  14. window.top.location = window.location;
  15. }
  16. })(this);
  17. </script>

方法二:

  1. <script>
  2. // A more cryptic one-liner, to awe & impress.
  3. //
  4. // No need to protect `window` since `this` is
  5. // immutable, and at the topmost level means
  6. // `window` anyways. Here, we compare locations
  7. // on the left side of the "&&" and execute the
  8. // code in parenthesis if that condition is
  9. // true (top location isn't iframe location).
  10. //
  11. // Otherwise, nothing happens. It's basically an
  12. // if statement without wrapping curly brackets.
  13. //
  14. // Weird, I know. But pretty cool, right? :)
  15. this.top.location !== this.location && (this.top.location = this.location);
  16. </script>

希望本文所述对大家的javascript程序设计有所帮助。

人气教程排行