tim peterson
tim peterson

Reputation: 24305

Detect if user has closed ALL windows for a website?

I know about this:

window.onbeforeunload = function() {
   //tell server user has left your site
};

but is there a client-side way to use javascript to detect if a user has closed ALL browser windows for your website?

Or do I need server-side code to detect this?

Upvotes: 7

Views: 2153

Answers (2)

RWAM
RWAM

Reputation: 7018

You can save an info into LocalStorage to detect any existence.

Some thoughts: on load you write the value to the sessionStorage:

window.onload = function() {
    if (sessionStorage.instances) {
        sessionStorage = Number(sessionStorage.instances) + 1;
    } else {
        sessionStorage.instances = 1
    }
}

and on unload decrease the value:

window.onbeforeunload = function() {
    var instances;

    if (sessionStorage.instances) {
        instances = Number(sessionStorage.instances) - 1;
        sessionStorage.instances = instances;
        if (0 === instances) {
            // all instances closed
        }
    }
}

Ciao Ralf

PS: Example taken from http://www.w3schools.com/html/html5_webstorage.asp and modified a little ;)

Upvotes: 6

Nikolay Ivanchev
Nikolay Ivanchev

Reputation: 144

You can generate a cookie with prefix like closed_tab_ and suffix lets say either a timestamp or an uuid. When closing a window delete the cookie set by this tab and check for other cookies using the same naming scheme.. That should solve the problem even with browsers without local storage As for crashed browsers - you can use a timer on every second to renew the cookie and set it to expire every second.. If you are not that time sensitive set it to larger value.

Upvotes: 0

Related Questions