6

I have a simple question - is there any way to read subdomain cookie on main domain by JavaScript? For example: I set cookie 'hello' with value '2' in subdomain yeah.something.com and after that I want to read it on something.com. I tried to find answer for that but I found only information how to set cookie on subdomain by creating it on domain.

Amay
  • 1,461
  • 5
  • 27
  • 56
  • Set the `domain` parameter when setting the cookie to `.something.com`. – CBroe Apr 09 '13 at 13:50
  • So the subdomain cookie should include 'domain' parametr? – Amay Apr 09 '13 at 13:55
  • Possible duplicate of [Reading Javascript Cookies from a subdomain](http://stackoverflow.com/questions/1688941/reading-javascript-cookies-from-a-subdomain) – Matt S Jun 03 '16 at 19:31
  • I've answered a [similar (possibly duplicate?) question](https://stackoverflow.com/a/67580590/15421144) that seems like it would help in this situation as well. – gurtner May 22 '21 at 02:09

1 Answers1

-1

An ancient question, but better to have it answered You can do it by creating a cookie on the domain with a dot on the start to support reading from all subdomains and from the main domain as well:

document.cookie = "_id=MY_ID;domain=.example.com;expires=;SameSite=none;Secure";

Hope it will help other lookers like me :)

Oded BD
  • 2,788
  • 27
  • 30
  • Browsers stopped recognizing the leading dot in `domain=` back in 2011 when RFC 6265 was adopted, so your information is very out of date: https://stackoverflow.com/a/20884869/159145 - from the spec: _"Note that a leading `%x2E` ("."), if present, is ignored"_ – Dai Jul 09 '22 at 02:11