使用 JavaScript 或其他方式在不同域上设置 cookie
我需要在浏览 second.example
时设置/获取存储在 first.example
的 cookie,我拥有对 first.example
的完全访问权限,但我在 second.example
上只有 JavaScript 访问权限(可以根据需要操作 DOM)。
我的第一种方法是在 second.example
(使用 JS)上创建一个 iframe,加载像 first.example/doAjax?setCookie=xxx
这样的页面,并执行 AJAX 调用比如说 first.example/setCookie?cookieData=xxx
,它将使用我们传递的数据在 first.example
上设置 cookie。
这对于在 first.example
上从 second.example
设置 cookie 来说效果很好 - 为了获取 cookie,我基本上遵循了相同的过程,创建了加载 的 iframe >first.example/doAjax?getCookie
,这将执行一个 AJAX 调用来表示 first.example/getCookie
,它将读取 first.example
上的 cookie 信息并将其作为 JSON 对象返回。
问题是我无法将该 JSON cookie 对象带回 second.example
以便我可以读取它,也许我可以在 AJAX 调用完成时使用“window.top”将其带回“但是存在时间问题,因为它与 iframe 加载的时间无关。 我希望我很清楚,并且想知道是否有一个更简单的解决方案,而不是这个疯狂的 iframe->ajax 废话,而且似乎这甚至无法在 SAFARI 中获取 cookie。
I need to set/get the cookies stored at first.example
while browsing second.example
, I have full access of first.example
but I only have JavaScript access (can manipulate the DOM as I want) on second.example
.
My first approach was to create an iframe on second.example
(with JS) that loaded a page like first.example/doAjax?setCookie=xxx
and that did an AJAX call to say first.example/setCookie?cookieData=xxx
which would set the cookie on first.example
with the data we passed around.
That pretty much worked fine for setting the cookie on first.example
from second.example
- for getting a cookie I basically followed the same procedure, created the iframe that loaded first.example/doAjax?getCookie
and that would do an AJAX call to say first.example/getCookie
which would read the cookie info on first.example
and return it as a JSON object.
The problem is that I'm unable to bring that JSON cookie object back to second.example
so I can read it, well maybe I could just bring it when the AJAX call is complete using "window.top" but there's timing issues because its not relative to when the iframe has been loaded. I hope I am clear and was wondering if there's an easier solution rather than this crazy iframe->ajax crap, also seems like this won't even work for getting cookies in SAFARI.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过回调将脚本元素注入到文档的 HEAD 中,该回调将您需要的 cookie 传递给任何需要它的函数。
类似于:
页面first.com/doAjax?getCookie 可以执行以下操作:
You could inject a script element into HEAD of the document with a callback that passes the cookie you need to whatever function needs it.
Something like:
And the page first.com/doAjax?getCookie could do this:
将此 PHP 文件放入 first.com:
在 secondary.com 上,您可以使用此 javascript 获取值:
问候,
罗伯特
Put this PHP-File to first.com:
On second.com you can use this javascript to get the value:
Regards,
Robert
对于设置 cookie,您可以按如下方式更改我的脚本:
新的 PHP 脚本:
和 JavaScript:
这应该适用于所有浏览器。
For SETTING cookies you can change my script as follows:
The new PHP-Script:
And the JavaScript:
That should work on all browsers.