I have an unload and beforeunload event defined as:
window.onunload = (function () {
alert("In unload); } ());
window.beforeonunload = (function () {
alert("In unload); } ());
When the page loads for the first time or after a postback (not before), the alert shows up. It shouldn’t. This happens in Firefox & Chrome but not in IE. Why? It seems IE has the correct behavior.
Okay, so first of all, you’re missing quotes on the
alerts, so it shouldn’t alert at all.To address your actual question, you’re invoking the function, not just declaring it.
(You also write
beforeonunload. That is incorrect. It should beonbeforeunload)That creates an anonymous function and invokes it immediately. They are generally called IIFE’s in JavaScript. To add an event handler, you have to pass a reference to a function. So the correct method here would be this:
In your case, what is being assigned to the event is
undefined, since your anonymous function doesn’treturnanything. It would work perfectly if itreturned a function.Chrome tends to block alerts onunload and onbeforeunload because those are generally spammy websites trying to prevent users from leaving. A
console.logworks perfectly, however. Check the demo. Open the console, click run, and since when you click run, the code is refreshed, the frame is reloaded, and you get the events being fired just before the page has been unloaded, and then loaded again.