Search code examples
google-chromejqueryonbeforeunload

Back button not triggering the method within the "beforeunload" in Chrome


Im using the jquery event beforeunload $(window).bind('beforeunload') to make an api call after a user closes the browser, or a tab, or hits the back button. It works fine in Firefox, but not completely in Chrome. In Chrome, it works when the user closes the browser or tab, but not when the user hits the back button. The method is supposed to remove the user from a list of "current active users" whenever they close the browser or tab or leave the page. For some reason in Chrome, the history api isn't removing the user whenever they leave the page via the back button. What could be causing this? Thanks.


Solution

  • I am not sure why this happens but, personally, I wouldn't rely on this. What if the users' computer crashes? A browser will not fire that event - it won't have the chance to. Best bet would be to call a page via ajax or something similar, every 5 seconds or so, and that page updates a date related to the user. You then show users where the date is within the last minute, or whatever you decide, in the list of currently active users. If their computer crashes, the date will no longer be updated.

    Regards, Clarkey