How to Prevent iFrame Breakaway

Few days ago I was searching for a solution to the problem I’ve encountered – I needed to prevent a third party page to break out of iframe inside a web page of my web application. For people who are not closely familiar with JavaScript, the following JS snippet will make it more clear how page can break out of iframe:

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

If the current page is not the parent window – become the parent window.

I needed to implement something on my end, that would block or prevent the above script or similar to it from executing. I’ve spent several hours browsing the Net, talking to people on IRC and simply playing trial and error.

After some time, I understood that I wont be able to find a solution to my problem, simply because there is none unfortunately. But, having said that, I have some findings to share:

  1. There is iframe security attribute which only works on IE. Setting this attribute to security=”restricted”, will prevent iframe to break out. Its always “nice” to see that MS have few tricks up their sleeve :). Also, on one of the forums, someone mentioned that the same attribute will work under Opera as well as under IE. I personally haven’t tested it my self under Opera, I can just say that it works for IE and not FF.
  2. To make use of window.onbeforeunload event and prompt user with a dialog that requires user’s input if he agrees to navigate away from the current page. If user disagrees (clicks “cancel”), he will remain on the current page. So here in a sense iframe breakaway was canceled. By the way, there is no way to suppress the dialog prompt and make event from clicking “cancel” default.
  3. To grab the content of third party page using PHP Curl lib and to create your own placeholder page for that content. Then the placeholder page can be put inside iframe. The page or the grabbed content will not attempt to breakout, but any request submitted to the placeholder page (hyper link or button click on the grabbed content) will cause page to unload.

Also, while researching, I came across this post that talks about preventing iframe breakaway and click jacking with the help of 204 header response code.

After all that, my conclusion is:
If the page inside iframe is not yours, in other words it is a page hosted under another domain, its not possible actually to stop a page from unloading. Having something like that, would allow malicious sites to “trap” a user indefinitely.

I would love to hear any other suggestions regarding iframe breakout you may have dear readers.

Cheers