简体   繁体   中英

JS Cookie set in 2 places, doesn't overwrite first set

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;
    }
}

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM