开发者

Javascript cookie expiration/deletion on different browsing scenarios

开发者 https://www.devze.com 2023-01-13 20:44 出处:网络
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.

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 in开发者_StackOverflowstead 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?


I don't think it's possible, but here's a list of the window events available to you.

* onafterupdate
* onBeforeunload
* onBeforeupdate
* onBlur
* onClick
* ondblclick
* onError
* onerrorupdate
* onFocus
* onhelp
* onkeydown
* onkeypress
* onkeyup
* onLoad
* onmousedown
* onmousemove
* onmouseout
* onmouseover
* onmouseup
* onragstart
* onreadystatechange
* onresize
* onrowenter
* onrowexit
* onscroll
* onselectstart
* onUnload 

Some of these may be obsolete.

Source


unload is 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消