A client requested cookie functionality where if the browser is not closed, the cookie has a 30 minute expiration, but then it needs to be removed if/when a user closes the browser.
Here’s how I was going to do it:
delCookie = function() {
document.cookie = 'cookieName=;expiration=Thu, 01-Jan-70 00:00:01 GMT;';
};
$(window).unload(function() {
delCookie();
})
I then realized that when user navigates to a different site, it also triggers .unload which will delete the cookie instead of keeping the cookie with expiration.
Is there any way I can detect using javascript when browser is being closed or a user is navigating away from the site?
unloadis the standard method of detecting that the user has left your site (either closed the window/tab or navigated away)You need to remember that if a user navigates away you cannot run code from your application anymore.
To answer your question – the code you posted is the most flexibility you will get with your scenario.