afemath
afemath

Reputation: 181

Javascript cookie without a leading dot

I want to clear a cookie using javascript that was originally created server-side. Whenever I create a cookie using javascript I get a leading dot on my domain so I cannot overwrite the server's cookie.

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

clearCookie('cookieTime');

This is the result of my cookie:

name: cookieTime
domain: .www.currentdomain.com
path: /

This is the cookie from the server:

name: cookieTime
domain: www.currentdomain.com
path: /

How do I create a js cookie without a leading dot?

Upvotes: 14

Views: 8192

Answers (1)

javierjv
javierjv

Reputation: 121

As you can see here you can get rid of the leading dot just by not setting the domain at all.

Also, consider you can only update your own cookies, so get rid of the domain in the function and update cookies set by server like:

function clearCookie(name, path){
    var path = path || "/";
    document.cookie = name + "=; expires=" + new Date() + "; path=" + path;
};

clearCookie('cookieTime');

Upvotes: 12

Related Questions