Xar
Xar

Reputation: 7940

Javascript setting cookies with path=/

I'm creating cookies which are intended to be shared all across mysite.

This is the code that creates such cookies:

var setCookie = function(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    var path ="path=/;";
    document.cookie = cname + "=" + cvalue + ";" + expires + ";" + path;
};

It looks pretty straight forward, and I'm using path=/ to indicate that I want to create or modify always the same cookie all along my site.

The problem is that it is creating one cookie for each URL. With a Mozilla plugin I can see the following:

Cookie Name         Value   Path
timer_is_enabled    true    /
timer_is_enabled    false   /foo
timer_is_enabled    true    /foo/bar

Which is causing my many bugs because the variables which are being accessed are not one and only, but many independent ones.

Any idea why I'm getting this behavior?

Upvotes: 2

Views: 85

Answers (2)

Álvaro González
Álvaro González

Reputation: 146563

Your code should work as expected, at least regarding the path attribute. Those other cookies may be remnants from earlier tests (sadly, there's normally no way to track the creation date of a given cookie since browsers don't normally keep such information).

I suggest you remove all current cookies from the browser and try again.

Upvotes: 1

Dean James
Dean James

Reputation: 2633

That function works ok for me. Ran the following:

setCookie('myCookieKey', 'myCookieValue', 10);

And I got the following:

enter image description here

Upvotes: 1

Related Questions