Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting setting cookies on different domains, with javascript or other

Tags:

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".

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.

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.

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.

like image 875
Luca Matteis Avatar asked Dec 31 '08 05:12

Luca Matteis


People also ask

Can JavaScript set cookie for another domain?

You cannot set cookies for another domain.

Can you set a cookie for multiple domains?

As you may know, cookie can't be set in a different domain from another domain directly. If you're having multiple sites in where you need to set a cookie from a parent site, you can use basic HTML and JS to set the cookies. Google is using this same way.

Can you set cookie on a different path?

You can't access cookies from a different path - otherwise it would be a security hole.


1 Answers

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:

 <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> 

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

     passCookie({'name':'mycookie', 'value':'myvalue'}); 
like image 50
Ryan Doherty Avatar answered Sep 21 '22 17:09

Ryan Doherty