Fire onbeforeunload once and then disable


I want to fire onbeforeunload event for once on my page and then disable it. I tried the following code but it doesn’t work. Any ideas about this?

var counter = 0;
window.onbeforeunload = function() {
	if (counter === 0) {
		return false;

Purpose: That will be used to bust iframe buster.

Can you give a use case? What is the scenario in which you would need to bust an iFrame buster?

Are you trying to do it from the framed page or the page that is doing the framing?

The value to be returned is the text to display in the dialog to ask if they have changed their mind. Returning false will allow the page to unload without asking.

So with the code you have it allows the page to be unloaded without asking the first time. The rest of your code never runs because the page is unloaded when it gets to the return false and never gets to run counter++ at all.

Only if you replace the return false on the first call with a message offering them the alternative of not reloading the page will the counter ever get incremented. Then you’d need to return false to stop the message appearing on subsequent calls so that it will automatically unload on the second call.

Thank you Stephen, your suggestion helped me modify the code and finally find the one that works. I will share it here in case someone else needs the same thing in the future:

var bust = 0;
window.onbeforeunload = function() {
	if (bust === 0) {
		return 'Stay on this page.';

Now, the alert is displayed only on the first attempt from the iframed page that tries to open itself in the top window. I need one more thing about this code. I want to make this code active only within a limited timeframe. For example it will become inactive after 3 or 5 seconds. Is something like that possible?

The following line of code should overwrite that event handler after three seconds:

setTimeout(function() {window.onbeforeunload = null;},3000);

Thank you very much Stephen.