2

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?

3
  • 1
    Just to ensure they aren't remnants from earlier tests, can you remove them all and try again? Commented Sep 27, 2016 at 8:13
  • You are right. I wasn't deleting all the cookies correctly. Thanks for your insight. Commented Sep 27, 2016 at 10:55
  • Glad you got it sorted out. I've composed a proper answer to help others in the future. Commented Sep 27, 2016 at 11:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

That function works ok for me. Ran the following:

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

And I got the following:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.