Search code examples
javascriptjqueryjsonjsonp

How read cookies by jsonp?


Hi I have this code that load a page from index.html:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.2.min.js"></script>
<script>
function jsonCallback(json){
  console.log(json);
  alert(document.cookie.json)
}

$.ajax({
  url: "https://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
  dataType: "jsonp"
});
</script>

I want get cookies, so in https://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json I've executed in Console: document.cookie='test=123' and return undefined. Why? How can I fix it?

Here's what that URL returns:

jsonCallback(
  {
    "sites":
    [
      {
        "siteName": "SitePoint",
        "domainName": "https://www.sitepoint.com",
        "description": "SitePoint is a hub for web developers to share their passion for building incredible Internet things."
      },
      {
        "siteName": "A List Apart",
        "domainName": "http://alistapart.com/",
        "description": "A List Apart explores the design, development, and meaning of web content, with a special focus on web standards and best practices."
      },
      {
        "siteName": "Smashing Magazine",
        "domainName": "https://www.smashingmagazine.com/",
        "description": "Smashing Magazine delivers useful and innovative information to Web designers and developers."
      }
    ]
  }
);

Solution

  • You can't use JavaScript code in your page to read cookies for other origins. If you have http://example.com/foo.html and in it you load a script (which is what you're doing with JSONP) from http://api.com/, any cookies returned with the response from http://api.com/ are associated with http://api.com/. You can't read them with JavaScript code in http://example.com/foo.html.