Re: simple javascript cookie question

Giganews Newsgroups
Subject: Re: simple javascript cookie question
Posted by:  Alvaro G. Vicario (webmast…@NOSPAMdemogracia.com)
Date: Wed, 6 Sep 2006

*** alex.kemsley escribió/wrote (5 Sep 2006 07:13:54 -0700):
> I am trying to write a simple script in vain.
> I need it to first check to see if the cookie exists
> then if not
> write one with two variable
[...]
> I need this cookie to last just one day.

I compiled these functions some time ago, I hope it helps. (I've just translated the names from Spanish using Search & Replace, I hope I didn't break it)

/*
* Creates a cookie - name [value] [timeToExpire (s)] [path] [domain] [secure (bool)]
*/
function createCookie(name, value, timeToExpire, path, domain, secure){ // v2005-03-02
    if(timeToExpire){
        var expires=new Date();
        expires.setUTCMilliseconds(expires.getUTCMilliseconds()+1000*timeToExpire);
    }

    document.cookie=escape(name) + '=' + (value? escape(value) : '') +
        (expires? '; expires='    + expires.toGMTString() : '') +
        (path?    '; path='        + escape(path) : '') +
        (domain? '; domain='      + escape(domain) : '') +
        (secure?  '; secure' : '');
}

/*
* Removes a cookie
*/
function removeCookie(name){ // v2005-03-02
    createCookie(name, '', -86400*365*10);
}

/*
* Returns the value of a cookie (null if it doesn't exist)
*/
function readCookie(name){ // v2005-02-27
    eval('var re=/^('+escape(name)+')=(.*)$/i;');
    var c=document.cookie.split(/;\s*/);

    for(var i in c){
        if(re.test(c[i])){
            return unescape(re.exec(c[i])[2]);
        }
    }
    return null;
}

--
-+http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
++ Mi sitio sobre programación web:http://bits.demogracia.com
+- Mi web de humor con rayos UVA:http://www.demogracia.com
--

Replies

In response to

simple javascript cookie question posted by alex.kemsley on 5 Sep 2006