0

In a Chat application that I am developing, I must call a function that cleans up connections when the User closes the Chat Window. The Chat Window is in a popup browser. ("closes" meaning the user presses the red 'x' of the window).

I have been able to detect the close event and call the function simply in IE11 using the onbeforeunload event handler.

IE11 Code:

 window.onbeforeunload = function() {             
    cleanUp();
 };

However, now I must do the same for Chrome, but there seems to be a "Leave this Page/Stay on this Page" popup that occurs when the User tries to exit (that is, with my beforeunload handler in place). I would rather the user could exit cleanly and not be interrupted by this message.

Furthermore, my function is not getting called in my handler in Chrome. I'm not sure why.

Is there a way to bypass the popup message in Chrome, or is this considered bad practice? Also, how do I ensure my function gets called, upon window close?

I have seen the following being used to detect the close event in Chrome:

Chrome Code:

var unloadEvent = function (e) {
    var confirmationMessage = "Are you sure you want to leave?";
    (e || window.event).returnValue = confirmationMessage;
    return confirmationMessage;
};

window.addEventListener("beforeunload", unloadEvent);

And I have tried modifying it to call my function like so:

Chrome Code Modified:

var unloadEvent = function (e) {
    var confirmationMessage = "Are you sure you want to leave?";
    (e || window.event).returnValue = confirmationMessage;
    return cleanUp(confirmationMessage);
};

window.addEventListener("beforeunload", unloadEvent);

Note: I read that the beforeunload handling here in Chrome expects a return String, so I call my cleanUp function to return the confirmationMessage String from there, while also calling my clean up code.

Any help appreciated.

Thanks, Dearg

Dearg
  • 57
  • 2
  • 9
  • 1
    Check this question [window.onbeforeunload ajax request problem with Chrome](http://stackoverflow.com/questions/4945932/window-onbeforeunload-ajax-request-problem-with-chrome) mention by @CherryDT in deleted answer. – jcubic May 04 '16 at 13:37
  • If you don't return anything in `onbeforeunload` there will be no popup. – jcubic May 04 '16 at 13:42
  • @jcubic are you referring to Chrome? It's the popup in Chrome that is giving me trouble, where I am using "beforeunload". – Dearg May 04 '16 at 14:26
  • jcubic that link you posted solved my problem! Specifically, the post by @Mohoch in that thread, that code worked perfectly! I'm not sure how to mark your comment as having answered my question..but I upvoted your comment! :) – Dearg May 04 '16 at 15:26

0 Answers0