Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete cookies using javascript after certain time

I am trying to delete a the value cookie that I created after a certain interval. Lets say after 10 second I want the cookie gone

function fullday()
{
    document.getElementById("res").innerHTML="1 day";
    document.cookie="day="+1;
    document.cookie.setMaxAge(0);
}

This is the code above. I'm coding in PHP right now and then when I try to destroy cookie from PHP it works fine, however I need to pass the cookie's value in javascript so now im stuck with it and cannot destroy it.

like image 760
freaky Avatar asked Feb 18 '23 21:02

freaky


2 Answers

In order to delete a cookie you need to set the expiry date to something in the past. A function that does this would be for example:

var delete_cookie = function(name) {
    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};

Then to delete a cookie named "cookie" just do.

delete_cookie('cookie');
like image 113
Bud Damyanov Avatar answered Feb 21 '23 17:02

Bud Damyanov


pass cookie name at "key"

 _generatePrefix: function()
    {
        return '__session:' + this._id + ':';
    }
  _cookieCache: undefined,
function cookie clear(key)
  {    
    document.cookie = this._generatePrefix() + key + '=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    delete this._cookieCache[key]
  }

call this function when u need clear specific cookie

if u want clear all cookie use this

   _generatePrefix: function()
    {
        return '__session:' + this._id + ':';
    }
     _cookieCache: undefined, 
     function clearall()
    {
        for (var i in this._cookieCache) {
            document.cookie = this._generatePrefix() + i + '=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        }
        this._cookieCache = {};
    }
like image 27
Nilesh patel Avatar answered Feb 21 '23 17:02

Nilesh patel