简体   繁体   中英

JavaScript's document.cookie does not replace cookie in the subdomain

I'm having trouble setting cookies.

When I call document.cookies = "cookieName=cookieValue;path=/;domain=domain.com"; from a subdomain like "subdomain.domain.com", Chrome shows the cookie being set on both, the domain and the subdomain I'm in. This is not ideal, since I only want to set it on the domain, but for now it's fine with me.

The problem is when I want to replace the cookie. If I call the same line but with a different cookie value like document.cookies = "cookieName=cookieValue2;path=/;domain=domain.com"; , Chrome shows the cookie getting replaced in the domain, but not the subdomain. This is a problem.

Can someone help me with this?

Well, not sure what's happening with this, but the work around I found was to simply set the cookie twice: one without specifying the domain (which replaces the subdomain cookie) and one for the domain:

document.cookies = "cookieName=cookieValue;path=/"; //Replaces the subdomain cookie
document.cookies = "cookieName=cookieValue;path=/;domain=domain.com"; //Replaces the domain cookie

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