changepicture
changepicture

Reputation: 466

Access cookies set on subdomain from parent

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

Answers (1)

Quentin
Quentin

Reputation: 943142

This is the expected behavior.

JavaScript can only access a cookie that if the domain of the cookie is either:

  • An exact match for the hostname of the current page
  • A substring of the hostname of the current page

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:

  • Change the domain specified when you set the cookie
  • Dynamically generate the JS file on the server and insert the data using server-side programming (the browser will send the cookie in the HTTP request header when requesting the JS URL because the domains match).

Upvotes: 2

Related Questions