Is there a way to run a final JavaScript code when a user closes a browser window or refreshes the page?
I'm thinking of something similar to onload but more like onclose? Thanks.
I don't like the onbeforeunload method, which always yields to a confirmation box popping up (leave page/ stay on mozilla) or (reload/ don't reload on chrome). Is there a way to execute the code quietly?
There is both
window.onbeforeunload
andwindow.onunload
, which are used differently depending on the browser. You can assing them either by setting the window properties to functions, or using the.addEventListener
:Usually,
onbeforeunload
is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving).onunload
isn't supported by Opera, as far as I know, but you could always set both.jQuery version:
Update: jQuery 3:
Thanks Garrett
The event is called
beforeunload
, so you can assign a function towindow.onbeforeunload
.You can try something like this:
You can use
window.onbeforeunload
.The documentation here encourages listening to the onbeforeunload event and/or adding an event listener on window.
You can also just populate the .onunload or .onbeforeunload properties of window with a function or a function reference.
Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.