html javascript iframe

iframe: avoid page reload

Say you want the users of your website to be able to add to their profile page an iframe with an external url loaded, their blog for example.
Easy, isn't it?
I did it and then discovered an hidden issue: some popular website, has coded a javascript function that checks if the website is been loaded into an iframe, then it jumps out and load in the main window, with the result that the pour users of your website can't access their profile page anymore!!
What those website have is something like:

if ( top != self.parent )
   top.location = self.parent.location;

What we need to do here to workaround this is handling the onbeforeunload event. This event get fired just before the window where the website is loaded, loads another website or get closed. This means that if an iframe in our website is trying to load itself in the main window, this call get called.
Let's see then what we can do:

window.onbeforeunload = function (e) {
  var e = e || window.event;

  // For IE and Firefox
  if (e) {
    e.returnValue = '';
  }

  // For Safari
  return '';
};

This script will prompt you an alert message asking if it's your intention to leave the current page.
Because you don't want to have this alert on any time you leave the page, you could use a flag that expires 15-30sec after the creation of the iframe element and then check the value of this flag in the onbeforeunload event function.
Doing so you will receive the confirmation alert only if you leave the website in those 30sec when the iframe is loading which might be the cause of firing the onbeforeunload method.

Unfortunately this code isn't supported (yet) in Safari and gets ignored.

Share and Enjoy: