I want to call a javascript function when a user closes a popup window (I'm not doing anything evil. I just want to clear out some session stuff)... but NOT when that window is reloaded. In IE I can use onunload to do it. But in Firefox it runs whenever the window is reloaded. Any idea how to rig it?
People succeed in answering ParagramStudios's questions 26% of the time (9 successes in 34 attempts).
Answers by: darksanity | vlambert | speed
This is a difficult one. The trouble is that to JavaScript, all of these events (closing, reloading, redirecting, etc.) are the same thing. So the script has no way to know which is which.
A quick bit of research did come up with a useful trick though.
Hold the page in a frameset. Attach the onunload event to the frameset page, _not_ the page inside it. When they close the window, it will fire. If they click a link in the page, it will not. If you reload the page with script, it will not fire. If they right click and refresh, it will not fire. If they have a refresh or reload button (if you did not hide it using window.open), it _will_ fire. There is nothing that you can do to prevent that, except hiding the button using window.open to open the window without the menu bar. Usefully, this technique also works fully cross browser.
some similar articles:
http://dotnetjunkies.com/WebLog/familjones/archive/2004/04/06/10884.aspx
http://www.irt.org/script/1230.htm
Hope this is useful
I've seen that solution... it is not viable for what I'm doing. Nice try though.
Having things in frames starts to screw up things (the system is all ajaxy and junk and a convulted mess of httprequest and iframe loading). I started to do it that way and hit some road blocks and decided it was too much trouble.