How to delete cookies in JavaScript

{0 Comments}

To delete cookies of a browser using JavaScript there are many ways which developer uses.

Setting past date for expiry

 One of popular practice is to overwrite the cookies expiration time and then set it some date that which have passed. So it will get removed after setting the session value to expired date. This method is popular among developers.  

 Javascript |  copy code |? 
1
document.cookie='cookiename=;'+
2
    'expires=Thu, 01-Jan-70 00:00:01 GMT;'+
3
    'path=path;'+
4
    'domain=domain";

or you can use following function to clear all cookies form the domain you have providedd

 Javascript |  copy code |? 
01
function deleteAllCookies() {
02
    var cookies = document.cookie.split(";");
03
 
04
    for (var i = 0; i < cookies.length; i++) {
05
     var cookie = cookies[i];
06
     var eqPos = cookie.indexOf("=");
07
     var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
08
     document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
09
    }
10
}

Wait for closing of browser

Usually session value is deleted when user closes its browser. If it is not necessary to delete forcefully then it automatically get deleted when the browser is get closed.    

Leave a Comment

Your email address will not be published.