Skip to content
Advertisement

How to prevent IFRAME from redirecting top-level window

Some websites have code to “break out” of IFRAME enclosures, meaning that if a page A is loaded as an IFRAME inside an parent page P some Javascript in A redirects the outer window to A.

Typically this Javascript looks something like this:

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

My question is: As the author of the parent page P and not being the author of the inner page A, how can I prevent A from doing this break-out?

P.S. It seems to me like it ought to be a cross-site security violation, but it isn’t.

Advertisement

Answer

Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page.

Example: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

In HTML5 you can use sandbox property. Please see Pankrat’s answer below. http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement