How to delete browser cookies using javascript?

How to delete session information from my browser using javascript? Can this be done?

+3
source share
4 answers

Session information is usually stored on the server. An HTTP request for a page that destroys a session usually does the trick (using AJAX if you want).

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

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

Basically, all you need to do is set the cookie expiration date to some past date.

var cookie_date = new Date ( );  // now
cookie_date.setTime ( cookie_date.getTime() - 1 ); // one second before now.
// empty cookie 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 information.

+1

If you do not set an expiration date for the cookie, by definition it is only a session. I.e. it will be deleted when the user closes his browser. Thus, there is no need for cleaning.

0
source

In addition to the expiration, we write the value "deleted" or similar to a cookie. In some cases, we found that cookies do not expire immediately and accessing them from js can give false results in a short time.

0
source

Source: https://habr.com/ru/post/1698953/


All Articles