gravityboy
gravityboy

Reputation: 817

"onbeforeunload" not firing on unload

I stuck this in a .js file...

window.onbeforeunload = alert('onbeforeunload');

But it fires when the page is loaded, not when it is unloaded.
Does anyone know why?

Upvotes: 1

Views: 1359

Answers (2)

canon
canon

Reputation: 41675

You have to wrap it... try this instead:

window.onbeforeunload = function(){alert('onbeforeunload')};

Upvotes: 1

kemiller2002
kemiller2002

Reputation: 115488

change this:

window.onbeforeunload = alert('onbeforeunload');

to this

window.onbeforeunload = function () {alert('onbeforeunload');}

onbeforeunload takes a function reference which it will fire on before unload. You are technically assigning the return value of a function as the alert is firing when it is encountered on the page.

Upvotes: 10

Related Questions