Reputation: 466
I am trying to access a cookie set on a subdomain (small.example.org
) from the parent domain (example.org
) and I would like to do this from a bit of Javascript within the page.
First of all I am setting a cookie for the domain small.example.org
document.cookie = "name=Mike; domain=small.example.org"
When I load small.example.org
I can successfully see the cookie that I just set. When loading example.org
I cannot see any cookies from small.example.org
. Maybe not that surprising.
So I figured I need to make a request to the subdomain to include something onto the main domain, a script tag.
<script src="small.example.org/script.js"></script>
Now when I load example.org
with the request to the script tag and have a look in the browser, I can see the cookie from small.example.org
.
But when I try to access it from Javascript using document.cookie
, I get nothing.
Is this the expected behavior? I thought you cannot access cookies from Javascript only if they had the HTTPOnly
flag set.
Is there a way to go around this? The example above is very close to my actual use case scenario and unfortunately I cannot play too much with the architecture.
Upvotes: 1
Views: 446
Reputation: 943142
This is the expected behavior.
JavaScript can only access a cookie that if the domain
of the cookie is either:
example.org
can't read cookies for small.example.org
(although the reverse is not true).
Note that the Origin for JavaScript is determined by the URL of the HTML document the JS is running in, not by the URL that the JS was loaded from.
You can either:
domain
specified when you set the cookieUpvotes: 2