Bronzato
Bronzato

Reputation: 9332

Running some code when browser is closed

I have a website where each pages need to check if user close the browser, in this case I run some code (releaseLocking).

So on these pages I have implemented this code:

    $(window).on('beforeunload', function () {
        return "Are you sure you wanna quit ?";
    });
    $(window).unload(function () {
        releaseLocking();
    });

It works but I noticed that if I navigate to multiple pages where this code is implemented, when closing the browser, I'll have multiple call to releaseLocking (for each previously visited pages).

I would prefer only run this code for the last page really active. Do you see what I mean?

Do you have any idea how to proceed?

Thanks.

Upvotes: 3

Views: 1766

Answers (3)

Damien Overeem
Damien Overeem

Reputation: 4529

I suggest using localStorage for this. Since localStorage stores variables per domain, it will allow you to check if the code was already executed. Localstorage is also bound to the session, so after the browser is fully closed, your session is gone, causing the localStorage to be cleared so it wont interfere with the next session.

$(window).on('beforeunload', function () {
        return "Are you sure you wanna quit ?";
});
$(window).unload(function () {
    if ( !localStorage.getItem('lockReleased') ) {
        releaseLocking();
        localStorage.setItem('lockReleased', true)
    }
});

The code above will set localStorage variable lockReleased to true for the first window that closes. The other windows will see the value, and won't call releaseLocking.

Upvotes: 1

Niccolò Campolungo
Niccolò Campolungo

Reputation: 12042

I am not sure this is the only way to do it(neither the best), anyway you should be able to save a sort of session of the user and ask everytime to the server if the page is the last opened.

//the var declaration goes at the beginning of the script
var isLastPage = false;
$(window).on('beforeunload', function () {
    //ajax request, the callback will set isLastPage to true if it is the last page opened by the user with that session.
});
$(window).unload(function () {
    if(isLastPage) releaseLocking();
});

Server side you should create a session wich stores all the pages of the user(remember to update it via JS when the user closes a page or opens a new one). I think that only via JS is not possible to do it, you need to be helped by the server.

Upvotes: 0

PSR
PSR

Reputation: 40318

In my knowledge it is impossible to detect a browser close separately from a browser navigation. the browser does not provide the window with that information.

SEE HERE ALSO

Upvotes: 0

Related Questions