简体   繁体   中英

Subdomain read and delete primary domain cookie

I need to set a cookie from my main domain, read then remove the cookie from a subdomain. But I also need to possibly set that cookie again on the domain in the future, and read it later on the subdomain. Basically, a stream of one-way communication. I cannot have the main domain handle unsetting the cookie, because it could be months between users hitting the main domain and the subdomain.

I set a cookie on my domain, like so:

document.cookie = "mycookie=testcookie;domain=example.com;max-age=31536000;";

I access it just fine on another subdomain, as such:

document.cookie.replace(/(?:(?:^|.*;\s*)testcookie\s*\=\s*([^;]*).*$)|^.*$/, "$1");

I then try to kill it from the subdomain:

document.cookie = "mycookie=;domain=example.com;max-age=0;";

That does not work. Cookie is still set.

However, setting it like this clears it:

document.cookie = "mycookie=;domain=example.com;max-age=31536000;";

It now returns "" when asking for it from the subdomain.

But... if I go back to the domain and set it again, and I can see it has been set, the subdomain still returns ""

Is there some sort of... hierarchy of cookies I'm missing? I'm unsure how this behaves or how to overcome this.

In order to enable this you have to place a period . before the root domain, like so: .example.com This is important because of the way the cookie standardization is setup. This format should be compatible with most modern browsers.

In addition, the path must be identical when accessing or modifying the cookie across different subdomains. The easiest way to do this is to just use the root path for the domain, / . For example, if you set the cookie from sub1.example.com/page1 and try to access it from sub2.example.com/page2 , even though you set the domain as .example.com you also have to set the path=/ in order to access it and modify it from any path on other subdomains.

Ultimately:

document.cookie = "mycookie=testcookie;domain=.example.com;path=/;max-age=31536000";

will enable you to set it and

document.cookie = "mycookie=;domain=.example.com;path=/;max-age=0";

will let you delete it.

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