Find browser close / update using javascript / jquery

  • Can anyone explain if there is a way to distinguish between closing the browser and updating events using javascript / jquery.
    Basically, I need to log out if it closes the tab.

    I tried using jQuery .unload () . But it shoots for Refresh and Form Submit. I tried to assign a global variable and avoided .unload () while submitting the form. But how can this be avoided for Refresh, or if there is some other work for this.

  • I wonder if this can be done only if the window is closed (instead of a bookmark).

+4
source share
4 answers

You may not be able to do this, except for some cookie-based methods, such as fake cookies, that work. Secondly, itโ€™s not so easy to distinguish between page refresh, form-based page redirect, or browser shutdown. It is difficult to determine, as far as I know.

You can do some little things before the client closes the tab. javascript detect browser close tab / close browser , but if your list of actions is large and the tab closes before it is completed, you are helpless. You can try, but with my experience donot depend on it.

window.addEventListener("beforeunload", function (e) { var confirmationMessage = "\o/"; /* Do you small action code here */ (e || window.event).returnValue = confirmationMessage; //Gecko + IE return confirmationMessage; //Webkit, Safari, Chrome }); 

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload

+1
source

You can try to use the cookie of the instance, that is, that is deleted after closing the browser, then you can check for the presence of cookies in JavaScript. otherwise, I donโ€™t think there is a way to tell the difference you are looking for simply using javascript.

+2
source

Unfortunately, JavaScript only provides onunload , which will fire whenever a user navigates from, closes, or reloads the current page.

Robert is right, this is a good situation for a session cookie: if you create a cookie without specifying a validity period, it will expire when the user tab / window is closed.

+2
source

Unfortunately, the implementation of onunload or onbeforeunload is not so great between browsers, and in case of failure, the unload event will never be fired. Itโ€™s best not to worry about catching unloading events and just have reasonable deadlines.

If you don't need to worry about the difference between form submissions and updates, you could get pretty good coverage with onunload, but it still won't be 100%.

0
source

All Articles