简体   繁体   中英

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.

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');

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 = {};
    }

use it like this

var date1 = new Date();
date1.setTime(date.getTime()+(10*1000));
var expires = "; expires="+date.toGMTString();

document.cookie = "day="+1+expires;

this will expire the cookie after 10 seconds.

The first question to ask is why you didn't just the cookie expiry time when you created the cookie?

The second question to ask is how did you create the cooklie? Via Javacript or PHP?

You can't retrieve anything other than the cookie value in javascript - hence if you want to know how old a cookie is, then you'd need to embed that information in the value - however if the cookie is set from PHP, and with a TTL of 10 seconds, you're going to run in clock sync issues - you'd need to generate javascript to create the timestamped cookie from serverside rather than callnig setcookie directly.

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