views:

382

answers:

3

Hi folks,

I'm trying to open a modal window when the browser window closes. Is there a way to do this with window events? Thanks.

+2  A: 

onbeforeunload is probably your best bet.

CptSkippy
onbeforeunload can't distinguish between browser closing, and navigating to another page...
Stobor
A: 

Short answer: no: Most browsers don't let you know when the browser is being closed.

See also:

http://stackoverflow.com/questions/299679/java-servlet-how-to-detect-browser-closing

http://stackoverflow.com/questions/317042/how-capture-event-for-browser-closing-in-web-applications

Stobor
This isn't accurate in my experience. I've been using onbeforeunload for years and almost never run into any issues.
Jon
@Jon: technically Stobor is right, onbeforeunload fires when a page unloads which happens not just when the browser is closing but also when you're navigating away from the page.
CptSkippy
@CptSkippy: That's a good distinction. It's hard to say if the OP was trying to be that specific.
Jon
Thanks guys! That event will do it.Actually, I need to catch the user closing the browser as well as navigating away.
A: 

You can execute whatever you need to with the onunload JavaScript event. I'd probably do a window.open rather than try to create a modal because I think the browser will still close. You could use the onbeforeunload event to show a modal confirming their action if that's what you're hoping to do.

Jon
I'll give it a try. Thanks.