Reputation: 777
I have an angular application where, when a user logs in, I set his status to "online" on the db. If this user close the browser, instead of performing the menu action logout, how can I update his status to "offline"? I tried to use the "$window.onbeforeunload" event and call a web service to logout the user. The code runs but it seems that the execution would be "cut off" by the browser: the service is never called "really".
Upvotes: 0
Views: 2217
Reputation: 10714
Use a WebSocket connection or polling, and listen for that to close/stop on the server.
As @António says, you cannot rely on the client to consistently notify you that it's closing.
Upvotes: 2
Reputation: 981
One thing to note is that the onbeforeunload event is not supported by all browsers, it's a non-standard event.
Also, your use-case has the caveat of firing that event whenever a user submits a form, navigates out of the page, etc.
You'd need to filter out those "events" from the onbeforeunload to make sure that your logic would only execute with an actual window close.
You can do that using jQuery:
var ignore;
$('a').live('click', function() { ignore = true; });
etc...
$(window).bind("beforeunload", function() {
return ignore || confirm("Do you want to close the browser/tab?");
});
The problem is that even with this, after clicking OK any subsequent code would never be executed because...well, the window is effectively closed :)
The only way you could do this was if, for some awkward reason, you could «prevent» the window from Closing while your logic was executed, and Closing it afterwards.
FORTUNATELY this is not possible.
So this leaves you with the only way of doing this properly wich is on the server-side, checking for session expiration or something like that.
Upvotes: 2