简体   繁体   中英

How can I delete my browser cookies using javascript?

How can I delete the session information from my browser by using javascript? Is it possible to do?

Session information is usually stored on the server. An HTTP request to a page that destroys the session would normally do the trick (using AJAX if you wish).

For cookies you can set the cookie expiry date to the current date, this will expire the cookie and remove it.

var d = new Date();
document.cookie = "cookiename=1;expires=" + d.toGMTString() + ";" + ";";

Basically all that you need is to set cookie's expiry date to some date in the past.

var cookie_date = new Date ( );  // now
cookie_date.setTime ( cookie_date.getTime() - 1 ); // one second before now.
// empty cookie's value and set the expiry date to a time in the past.
document.cookie = "logged_in=;
                  expires=" + cookie_date.toGMTString();

Click here or here for more informations.

If you don't set an expiry date to a cookie, by definition it is only session lived. Ie. it will be deleted when the user will close his browser. Thus, no need for clean up.

In addition to the expiration we have been writing a value "deleted" or similar to the cookie. In some cases we've discovered that the cookies don't expire immediately and accessing them from js might give false results for a short while.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM