获取在不同的域,使用javascript或其他设置Cookie [英] Getting setting cookies on different domains, with javascript or other

查看:202
本文介绍了获取在不同的域,使用javascript或其他设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有能够找到任何特殊的这种情况在线,所以这里我去...
我需要设置/获取cookie存储在first.com浏览second.com我有完全访问first.com,但我只有javascript访问(可以操纵DOM,我想要的)在second.com。

Haven't been able to find anything particular to this situation online so here i go... I need to set/get the cookies stored at "first.com" while browsing "second.com", I have full access of "first.com" but i only have javascript access (can manipulate the DOM as i want) on "second.com".

我的第一种方法是在second.com(使用js)上创建一个iframe,它加载了一个页面,如first.com/doAjax?setCookie=xxx,并执行了一个ajax调用说first.com/setCookie?cookieData=xxx使用我们传递的数据设置first.com上的cookie。

My first approach was to create an iframe on second.com (with js) that loaded a page like "first.com/doAjax?setCookie=xxx" and that did an ajax call to say "first.com/setCookie?cookieData=xxx" which would set the cookie on "first.com" with the data we passed around.

对于在second.com上设置first.com上的cookie非常有效 - 为了获取一个cookie我基本上遵循相同的过程,创建了iframe加载 first.com/doAjax?getCookie,这将执行ajax调用说first.com/getCookie,它将读取first.com上的cookie信息,并将其作为JSON对象返回。

That pretty much worked fine for setting the cookie on first.com from second.com - for getting a cookie I basically followed the same procedure, created the iframe that loaded "first.com/doAjax?getCookie" and that would do an ajax call to say "first.com/getCookie" which would read the cookie info on first.com and return it as a JSON object.

问题是,我无法将那个JSON cookie对象返回到second.com,所以我可以读它,也许我可以只是带它Ajax调用使用window.top完成,但有时序问题,因为它不是相对于iframe已加载时。我希望我很清楚,想知道是否有一个更容易的解决方案,而不是这个疯狂的iframe-> ajax crap,也似乎这样甚至没有工作获得饼干在SAFARI。

The problem is that I'm unable to bring that JSON cookie object back to "second.com" 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 wont even work for getting cookies in SAFARI.

推荐答案

您可以将一个脚本元素注入到文档的HEAD中,使用一个回调函数来传递您需要的cookie,无论函数需要什么。

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.

如下:

 <script type="text/javascript">
   var newfile=document.createElement('script');
   newfile.setAttribute("type","text/javascript");
   newfile.setAttribute("src", 'http://first.com/doAjax?getCookie&callback=passCookie');
   document.getElementsByTagName("head")[0].appendChild(newfile);
 </script>

并且页面first.com/doAjax?getCookie可以这样做:

And the page first.com/doAjax?getCookie could do this:

     passCookie({'name':'mycookie', 'value':'myvalue'});

这篇关于获取在不同的域,使用javascript或其他设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆