Monday, July 25, 2011

Override javascript onbeforeunload event within iframe

Now I had a brilliant trick for you that want to disable certain javascript event in iframe. We know that it's impossible to disable javascript within iframe page, that usually had a different domain. In this tutorial I will show you how to override javascript onbeforeunload event within iframe, so it won't show an annoying message when you close the window.

javascript onbeforeunload will triggered the moment user close the window. slightly different with onunload event... :D
I'll show you 2 pages, 1 page contain iframe from another page:
Hope you understand what I mean... :D

<!-- page1.htm -->
<html><head></head>
<body onbeforeunload='alert("See you later");'>
This is page1.htm
</body>
</html>


<!-- page2.htm -->
<html><head></head>
<body>
<iframe src='page1.htm'></iframe>
</body>
</html>

Explanation:
Page1.htm is a page within your iframe that had a onbeforeunload event, which from another domain.

Page2.htm is your webpage that contain iframe with page1.htm as a source.
So, when you close your webpage, the onbeforeunload function within page1.htm will be triggered. Most of them will showing an annoying message box pop-up.

Next, we need to override this onbeforeunload event and get rid of this message box.
Very easy trick:
in your <body> tag, add onbeforeunload event too, but with document.write() instead of confirm or alert method.

Your page will be look like this:
<!-- page2.htm -->
<html><head></head>
<body onbeforeunload='document.write("closing window..");'>
<iframe src='page1.htm'></iframe>
</body>
</html>

Why it works?
When you close the page, the onbeforeunload event in your page will be triggered. It will clear the page and fill it with closing window.. message. The iframe code was there, but now it's already replaced by document.write.

The onbeforeunload within the iframe now terminated.. :D
You can close window without annoying popup message anymore.

No comments:

Post a Comment