简体   繁体   中英

“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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM