3

What I want to do is, to fire some function, only when user tries to close browser window by clciking on x button. But not on refresh, "back" button click events like following function does.

$(window).unload( function () { alert("Bye now!"); } );

So is there any way to achieve this? Thx in advance

heron
  • 3,611
  • 25
  • 80
  • 148
  • 1
    I don't think it's possible to distinguish those actions. – pomeh May 21 '12 at 21:08
  • Try using JavaScript to open your page in a new window, and use [this solution](http://stackoverflow.com/questions/781770/can-the-parent-window-be-notified-when-a-child-window-closes-on-a-diff-domain) to detect when it's closed. – Blazemonger May 21 '12 at 21:10

3 Answers3

1

No, this is not possible. The onbeforeunload event does something like this but that will always fire when the windows closes. It does not differentiate between the way in which the window got unloaded.

Koen Peters
  • 12,798
  • 6
  • 36
  • 59
1

you could try forcing the user to a default location hash of #default as soon as they load the page. Then, if the person navigates back with the back button you can detect this with either a timer or the window's "popstate" event. Then, you could do something at this point like send them to another url.

In this way you could detect a window CLOSE with the "onbeforeunload" event and a back button press with the method mentioned in the last paragraph. Messy but it works.

Steve Binder
  • 2,270
  • 1
  • 14
  • 6
1

Couple of answers pointing that you won't be able to achive this: How to distinguish Unload Event triggered by Refresh or Window Close? and How to distinguish Unload Event triggered by Refresh or Window Close? Both "workarounds" suggested are checking out mouse position and asking akinator.

Community
  • 1
  • 1
danielQ
  • 2,016
  • 1
  • 15
  • 19