从不同路径检索 cookie

发布于 2024-07-22 20:46:05 字数 145 浏览 3 评论 0原文

我当前的文档 URL 是 http://127.0.0.1/foo,我需要更改 http://127.0.0.1/bar 的 cookie 值。 document.cookie 为空,因为文档的 URL 是 foo。 目前,我只想读取 cookie 值。 有什么线索吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

最美不过初阳 2024-07-29 20:46:05

您不能从不同的路径访问 cookie - 否则这将是一个安全漏洞。

我能想到的唯一方法是让 /bar 设置一个 path=/ 的 cookie,以便 / 中的所有页面(包括 /foo) 可以访问它。

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.

寄离 2024-07-29 20:46:05

正如 JJ 和 grawity 所提到的,您无法从您的页面执行此操作。 但是,您有一个解决方法。

我。 放置一个指向 http://localhost/bar 的 iframe。 在存储 cookie 值的“栏”页面上有一个隐藏元素。 (让这个 iframe 大小为 1*1,这样它就不可见)。

二. 在“foo”页面上使用 JavaScript 来获取 cookie 值。

类似的方法(经过修改)也可以用于写入 cookie 值!

谢谢,

拉姆吉。

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.

纵情客 2024-07-29 20:46:05

创建 cookie 时,如果将路径设置为“/”而不是“foo”,您将能够在域中的任何位置读取它,包括“/foo”、“/bar”等。

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.

夜还是长夜 2024-07-29 20:46:05

您可以创建一个指向 /bar 内资源的 ,并跨框架脚本进入其中。 例如:

<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= 是一种防止意外 Cookie 名称冲突的便利措施。 鉴于不同的路径共享 JavaScript 起源,这不是一种有效的安全机制。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文