Retrieve a cookie from a different path

若如初见. 提交于 2020-01-01 04:19:15

问题


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?


回答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.




回答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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/945862/retrieve-a-cookie-from-a-different-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!