Reading Javascript Cookies from a subdomain
On a subdomain -- a.test.com -- I'm trying to read the cookies set at .test.com. If I use document.cookie in JS, all i'm getting are the cookies from a.test.com. What is the syntax or route to read the cookies from .test.com?
I'm pretty certain you can read up 开发者_StackOverflow-- from sub domain to fqdn -- but you can not read down -- fqdn to sub domain.
Thanks!
While setting the cookies at test.com example.com, make sure that you specify the cookie domain as ".test.com" ".example.com".
For example:
your_key_name=your_key_value;domain=.example.com;expires=...
I needed to pass a Shopify variable to a subdomain using a cookie and I was able to add this Javascript before the closing </body>
tag:
<script>
var nowCart = new Date();
var timeCart = nowCart.getTime();
var expireTimeCart = timeCart + 1000*36000;
nowCart.setTime(expireTimeCart); // " + nowCart.toUTCString() + "
document.cookie = "_count={{ cart.item_count }};domain=.example.com;expires=;SameSite=none;Secure=true";
</script>
Using the .
before the domain is what allowed the cookie to be read from the domain as well as any other subdomain. This should work vice-versa too.
Before the closing </body>
tag of the subdomain, this is the Javascript I used to read the cookie and do something with it:
<script>
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
var cookie_name = getCookie('_count');
var cartCount = document.getElementById('_count');
cartCount.innerHTML=cookie_name;
</script>
精彩评论