3

I am working on a simple chat script using Ajax and want to indicate when a user leaves the page. Have read several docs and found this works:

window.onbeforeunload = leaveChat;
function leaveChat(){
    ... my code
    return 'Dont go...';
}

Unfortunately (and logically), if they cancel the exit, my code is still executed and they are flagged as leaving even though they are still on the page? It should only execute if the confirm leaving the page. Any suggestions?

I would use onunload, but it doesn't seem to work in any of my browsers (Chrome, IE).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
CaveCoder
  • 31
  • 2
  • http://stackoverflow.com/questions/12103876/control-window-onbeforeunload-event – markasoftware Nov 20 '13 at 00:42
  • have that do a request to a server page where it starts a 30 second timer, and kicks the user from the room after that time (on the server). Then, on the client, when you sense `onbeforeunload` add a `focus` event listener to the window. If this is called within 30 seconds, send another request to the server that cancels the kick countdown. Also, when doing Ajax in `onbeforeunload`, make sure to add `false` as a third argument to `xhr.open` – markasoftware Nov 20 '13 at 01:05
  • By any chance does your page use jQuery or ASP.NET ? – Yuriy Galanter Nov 20 '13 at 01:09

1 Answers1

0

First, you should add the event handler using:

window.addEventListener('beforeunload', function() {
    // Confirmation code here
});

window.addEventListener('unload', function() {
    // fire pixel tag to exit chat on server here
    // UI interactions are not possible in this event
});

For further research:

unload event reference

beforeunload event reference

Window.onunload reference

philwills
  • 985
  • 4
  • 8