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

不想你离开。 提交于 2020-02-02 15:27:26

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/24370738/js-cookie-set-in-2-places-doesnt-overwrite-first-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!