Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 326
afemath Avatar asked May 22 '13 09:05

afemath


People also ask

What is Hostonly cookie?

Host Only cookie means that the cookie should be handled by the browser to the server only to the same host/server that firstly sent it to the browser.

Can you set a cookie in JavaScript?

Create a Cookie with JavaScriptJavaScript can create, read, and delete cookies with the document.cookie property. With JavaScript, a cookie can be created like this: document.cookie = "username=John Doe"; You can also add an expiry date (in UTC time).

Can cookies always be read by JavaScript?

httponly is a flag you can set on cookies meaning they can not be accessed by JavaScript. This is to prevent malicious scripts stealing cookies with sensitive data or even entire sessions. So you either have to disable the httponly flag or you need to find another way to get the data to your javascript.

Are cookies domain specific?

A cookie is associated with a particular domain and scheme (such as http or https ), and may also be associated with subdomains if the Set-Cookie Domain attribute is set.


1 Answers

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');
like image 107
javierjv Avatar answered Oct 21 '22 14:10

javierjv