Guid
Guid

Reputation:

Retrieve a cookie from a different path

My current document URL is http: //127.0.0.1/foo and I need to change the value of a cookie for http: //127.0.0.1/bar. document.cookie is empty because document's URL is foo. For the moment, I just want to read the cookie value. Any clue?

Upvotes: 18

Views: 27896

Answers (4)

bobince
bobince

Reputation: 536339

You can create an <iframe> pointed at a resource inside /bar, and cross-frame-script into it. eg:

<iframe src="/bar/blank.html" id="barframe"></iframe>

var barframe= document.getElementById('barframe');
var bardocument= 'contentDocument' in barframe? barframe.contentDocument : barframe.contentWindow.document; // IE compat
alert(bardocument.cookie);

Cookie path= is a convenience measure to prevent accidental cookie name clashes. Given that different paths share a JavaScript origin, it is not an effective security mechanism.

Upvotes: 16

rAm
rAm

Reputation: 1106

As JJ and grawity have mentioned there is no way you can do this from your page. However, you have a work around.

i. Place an iframe which points to http://localhost/bar. Have a hidden element on the "bar" page where you store the cookie value. (let this iframe be 1*1 size so it is not visible).

ii. Use JavaScript on "foo" page to fetch the cookie value.

A similar approach (with modifications) can be used to write the cookie value too!

Thanks,

Ramjee.

Upvotes: 4

grawity_u1686
grawity_u1686

Reputation: 16122

You can't access cookies from a different path - otherwise it would be a security hole.

The only way I can think of is making /bar set a cookie whose path=/ so that all pages in / (including /foo) could access it.

Upvotes: 5

JJ.
JJ.

Reputation: 5475

When you create the cookie, if you set the path to '/' instead of 'foo' you will be able to read it anywhere on the domain, including '/foo', '/bar', etc.

Upvotes: 25

Related Questions