views:

99

answers:

2

Hi guys, been bagging my head over some Javascript, please help, I cant see why it simply wont find my cookie in IE 7 or 8

I am setting the cookie true through another event, but I just want to see IE pick up the cookie which I initially set. Works in firefox too, thanks in advance.

var t=setTimeout("doAlert()",8000);
var doAlertVar = true;
document.cookie =  "closed=0;expires=0;path=";

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie;
    alert(ca);
    ca = ca.replace(/^\s*|\s*$/g,'');
    ca = document.cookie.split(';');

    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function doAlert(){

    if(readCookie('closed')==1){
        doAlertVar = false;
    }
    if(readCookie('closed')==0){
        alert("unlicensed demo version\nbuy online at");

    }
    t=setTimeout("doAlert()",5000);

}
A: 

You can also do this with a regex:

function readCookie(name, defaultValue) {
  var value = defaultValue;
  document.cookie.replace(new RegExp("\\b" + name + "=([^;]*)"), function(_, v) {
    value = v;
  });
  return value;
}
Pointy
+1  A: 

Where to begin..

setTimeout("doAlert()",8000);
// do not use strings as an argument to setTimeout, that runs eval under the hood.
// use
setTimeout(doAlert,8000);
// instead

document.cookie =  "closed=0;expires=0;path=";
// this is wrong, expires should follow the format Fri, 14 May 2010 17:22:33 GMT (new Date().toUTCString())
// path should be path=/
Sean Kinsey