Retrieve a cookie from a different path
Solution 1
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.
Solution 2
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.
Solution 3
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.
Solution 4
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.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
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?
-
Admin about 15 yearsI cannot change the cookie's creation and path. So it means it's impossible to access cookie of bar from foo?
-
Antimony over 11 yearsIt's not a big security issue because the cookie isn't really protected anyway. Due to SOP ignoring paths, cookie paths are not a meaningful security barrier.
-
Antimony over 11 yearsWouldn't this let anyone on the internet grab the cookie?
-
Antimony over 11 years+1 for pointing out that cookie paths aren't a meaningful security wall.
-
Iliya Kolev over 9 yearsThe path is a performance feature, not a security one... I was missing the "barframe.contentDocument" part. Thanks a lot. +1 from me.