0

Very simple question. I need to perform a task when the user closes his browser. I'm aware of the functions below:

$(window).bind("beforeunload", function() {
    return false; 
})

$(window).unload(function() {
    return false; 
})

But both of these - bring up an alert asking the user - "Stay on this page" - "Leave this page" (atleast on Chrome).

I dont want that to happen. I just want to perform a task when he closes it like updating the time on the DB as to when he left.

Any ideas Thanks

Gublooo
  • 2,550
  • 8
  • 54
  • 91
  • It's pretty not portable. Different browsers fire "unload" event for different things (when you navigate, when you close the window or else). Even the "beforeunload" event is not so reliable (= you have to test many combinations of browsers/versions). If you do not return anything the dialog shouldn't be shown, the return value can be used to prompt the user (like here on SO when you navigate away when editing an answer). Just do your stuff (possibly with an async ajax call and that's all, just consider it may be fired for a refresh too). – Adriano Repetti Jun 28 '12 at 10:50
  • Yes I see your point - Thanks – Gublooo Jun 28 '12 at 10:54

2 Answers2

1

This is impossible to be done cross browser properly since Opera does not actually support it :\ as stated here: cross-browser Onunload and Onbeforeunload ? (particularly opera 11) and in many other well documented places.

Also as others mention there are varying degrees of implementation, for example Firefox you can add your own message to the alert box that shows on beforeunload but in Chrome you cannot and it will just show a generic message of something that does not really make much sense.

Community
  • 1
  • 1
Sammaye
  • 43,242
  • 7
  • 104
  • 146
0

You can either save user presence periodically (using ajax) or just log the last request to the server (in the back-end).

Donatas Olsevičius
  • 1,350
  • 8
  • 13