Reading a cookie from a different domain

Reverend Bubbles picture Reverend Bubbles · Mar 30, 2016 · Viewed 45.6k times · Source

I'm developing a page/form for a campaign inside my company. However, the first step is to check if the person is logged in. This is easily checked against a cookie - CUSTOMER - that is set once they're logged in.

However: 1) I'm developing locally, not on the same domain, and, as a result can't see that cookie 2) The final campaign may or may not end up residing on the actual domain. They may end up using a vanity URL or something.

For purposes of this, let's assume I do NOT have access to the main domain where the cookie was set.

How can I read that cookie from off the domain? Oh, and since IT folks don't let us touch the back-end grumble, it has to be a JS solution.

Thanks!

Answer

Quentin picture Quentin · Mar 30, 2016

You can't.

The only cookies you can read with client side JavaScript are those belonging to the host of the HTML document in which the <script> is embedded.

By setting withCredentials you can support cookies in cross-origin requests, but they are handled transparently by the browser and JS has no direct access to them (the XHR spec goes to far as to explicitly ban getAllResponseHeaders from reading cookie related headers). The only way for a cross-origin request to get access to cookies is for the server (which you say you don't have access to) to copy the data into the body or a different response header).