Handle Browser Close in JavaScript

Handle Browser close in JavaScript?

No. You only have onbeforeunload event, available as raw javascript (jquery doesn't include this event).

If you want to try it, try to post here an answer and, without pressing "post your answer" try to close the browser window.

This is the closest way to access the "close window" event.

How can I detect closing whole browser using javascript?

This is not an answer to the question in the title but solves the problem at hand (deleting a cookie on browser close) possibly in the most reliable way.

Use a session cookie!

They are deleted as the last browser window is closed. From MDN on document.cookie:

If neither expires nor max-age specified it will expire at the end of session.

Now what does "end of session" mean? This answer holds the... answer:

the cookie will then expire at the end of session (ie, when you close the browser)

There seem to have been some differences between browsers 5 years ago following this answer, however I am unsure about the current status of that. Depending on your usecase, this is still likely to suffice.

Detecting the browser closing through a JS event would be very unreliable due to conerns raised in @deceze's comment:

if you force-quit the browser or it crashes, the event won't fire either

Further than that, I don't think (although I don't have proof from any docs) that there is a respective DOM event for that to occur.

How can I handle browser tab close event in Angular? Only close, not refresh

This is, tragically, not a simple problem to solve. But it can be done. The answer below is amalgamated from many different SO answers.

Simple Part:
Knowning that the window is being destroyed. You can use the onunload event handle to detect this.

Tricky Part:

Detecting if it's a refresh, link follow or the desired window close event. Removing link follows and form submissions is easy enough:

var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });

$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});

Poor-man's Solution

Checking event.clientY or event.clientX to determine what was clicked to fire the event.

function doUnload(){
if (window.event.clientX < 0 && window.event.clientY < 0){
alert("Window closed");
}
else{
alert("Window refreshed");
}
}

Y-Axis doesn't work cause it's negative for clicks on reload or tab/window close buttons, and positive when keyboard shortcuts are used to reload (e.g. F5, Ctrl-R, ...) and window closing (e.g. Alt-F4). X-Axis is not useful since different browsers have differing button placements. However, if you're limited, then running the event coordinates thru a series of if-elses might be your best bet. Beware that this is certainly not reliable.

Involved Solution

(Taken from Julien Kronegg) Using HTML5's local storage and client/server AJAX communication. Caveat: This approach is limited to the browsers which support HTML5 local storage.

On your page, add an onunload to the window to the following handler

function myUnload(event) {
if (window.localStorage) {
// flag the page as being unloading
window.localStorage['myUnloadEventFlag']=new Date().getTime();
}

// notify the server that we want to disconnect the user in a few seconds (I used 5 seconds)
askServerToDisconnectUserInAFewSeconds(); // synchronous AJAX call
}

Then add a onloadon the body to the following handler

function myLoad(event) {
if (window.localStorage) {
var t0 = Number(window.localStorage['myUnloadEventFlag']);
if (isNaN(t0)) t0=0;
var t1=new Date().getTime();
var duration=t1-t0;
if (duration<10*1000) {
// less than 10 seconds since the previous Unload event => it's a browser reload (so cancel the disconnection request)
askServerToCancelDisconnectionRequest(); // asynchronous AJAX call
} else {
// last unload event was for a tab/window close => do whatever
}
}
}

On the server, collect the disconnection requests in a list and set a
timer thread which inspects the list at regular intervals (I used
every 20 seconds). Once a disconnection request timeout (i.e. the 5
seconds are gone), disconnect the user from the server. If a
disconnection request cancelation is received in the meantime, the
corresponding disconnection request is removed from the list, so that
the user will not be disconnected.

This approach is also applicable if you want to differentiate between
tab/window close event and followed links or submitted form. You just
need to put the two event handlers on every page which contains links
and forms and on every link/form landing page.

Closing Comments (pun intended):

Since you want to remove cookies when the window is closed, I'm assuming it's to prevent them from being used in a future session. If that's a correct assumption, the approach described above will work well. You keep the invalidated cookie on the server (once client is disconnected), when the client creates a new session, the JS will send the cookie over by default, at which point you know it's from an older session, delete it and optionally provide a new one to be set on the client.



Related Topics



Leave a reply



Submit