Why would setting [removed] not work in Chrome?

前端 未结 4 1032
逝去的感伤
逝去的感伤 2020-12-06 10:29

My coworker ran into an issue where NO cookie could be set on Chrome via code like this:

document.cookie = \"TEST=1; expires=Tue, 14 Oct 2014 20:23:32 GMT; pat

相关标签:
4条回答
  • 2020-12-06 10:54

    The expiry date set for the cookie might be the problem. I have come into a problem like this before on Chrome. Set the date to present or future date and test if it would work. Probably that was how Chrome was designed.

    0 讨论(0)
  • 2020-12-06 10:55

    The way cookies work, at least in Chrome, is a bit weird.

    If you need to change a cookie's value, then you need to add/set each keys one by one.

    Try this in your console:

    document.cookie; // -> "expires=Tue, 14 Oct 2014 20:23:32 GMT; path=/"
    document.cookie = 'TEST=1';
    document.cookie; // -> "TEST=1; expires=Tue, 14 Oct 2014 20:23:32 GMT; path=/"
    

    Yes, it has added the key, and not replace the whole cookie with TEST=1.

    If you need to remove a key, you can simple provide no value: TEST=.

    I hope this will get you out of the cookie nightmare (it was for me).

    0 讨论(0)
  • 2020-12-06 10:55

    As another user mentioned, you have to set them one-by-one. These functions can be useful in parsing & applying a cookie string:

    function clearCookies(){
        var cookies = document.cookie.split(';');
        for(i in cookies){
            var vals = cookies[i].split('=');
            var name = vals.shift(0, 1).trim();
            document.cookie = name+'=';
        }
    }
    function parseCookies(cookie){
        clearCookies();
        var cookies = cookie.split(';');
        for(i in cookies){
            var vals = cookies[i].split('=');
            var name = vals.shift(0, 1).trim();
            document.cookie = name+'='+vals.join('=');
        }
    }
    
    0 讨论(0)
  • 2020-12-06 11:02

    Make sure to run it on a server (at least a local server) so that document.cookie works.

    If you locally run this file in the browser. "document.cookie" wouldn't work.

    0 讨论(0)
提交回复
热议问题