Reputation: 7531
I am using the same script on 2 different pages, to set the same cookie. My assumption would be that even though the two pages are (slightly) different paths, they would simply overwrite the cookie instead of duplicating entries into it.
My first page's path is:
example.com/classifieds/businesses
My second page's path is:
example.com/classifieds/businesses/search
So, my question is, are cookies page-dependent; can I force them to overwrite existing values instead of writing their own page-specific values to the cookie?
Here is what my cookie looks like with the duplicates:
domain=.example.com; path=/; bdView=column; bdView=detail; domain=.example.com;
Code for setting domain (which is in the header file)
var domain = window.location.host.split(/\.(.+)/)[1];
document.cookie = "domain=." + domain;
document.cookie = "path=/";
Code for setting bdView (which is in a separate js file that I include in both pages)
function setCookie(view) {
switch (view) {
case "column":
document.cookie = "bdView=column";
break;
case "list":
document.cookie = "bdView=list";
break;
case "detail":
document.cookie = "bdView=detail";
break;
}
}
Upvotes: 3
Views: 2816
Reputation: 7531
So, I was simply using cookies wrong. I thought that domain & path were just their own things, but you're actually supposed to set them WITH the thing you're trying to set.
So, it should look like this instead:
function setCookie(view) {
var domain = window.location.host.split(/\.(.+)/)[1];
switch (view) {
case "column":
document.cookie = "bdView=column; path=/; domain=" + domain;
break;
case "list":
document.cookie = "bdView=list; path=/; domain=" + domain;
break;
case "detail":
document.cookie = "bdView=detail; path=/; domain=" + domain;
break;
}
}
Upvotes: 2