23

I have a function to create a cookie passing in the name, value and expiration (in days) of the cookie.

Here is the function:

function setCookie(c_name,value,exdays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : ";
    expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
}

The function works as expected, but what do I need to do to set the cookie never expire?

Lucky
  • 16,787
  • 19
  • 117
  • 151
John mido
  • 269
  • 1
  • 2
  • 10

2 Answers2

34

There is no way to set to never expire . It's not a javascript limitation, it's just not the part of the specification of the cookie http://www.faqs.org/rfcs/rfc2965.html.

You can set to a far date in the future. for example to set it for 20years from now call setCookie with 20*365 as exdays parameter as you setCookie function expect how many days before it expires. Like follows

setCookie('cookiename','cookie_val',20*365);
Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57
12

The variable exdays is how long it is until the cookie expires, just set that value to a couple of thousand days in your function call.

setCookie('cookiename', 'cookievalue', 10000); //expires in 10k days
adeneo
  • 312,895
  • 29
  • 395
  • 388