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) {
bust++;
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?