Search code examples
javascriptjqueryajaxsame-origin-policy

Same Origin Policy seemingly inconsistent using jQuery AJAX API


I'm trying to understand how the Same Origin Policy (SOP) applies in different situations.

I have the following JavaScript code written in a local HTML file and run with Chrome on Windows:

$(document).ready(function () {
    $.get("http://www.quandl.com/api/v1/datasets/FRED/GDP.json", function (r) {
        window.alert(r.source_name);
    });
});

It works by giving me data retrieved from another domain (www.quandl.com). However, if I swap that with google.com, the callback won't be invoked:

$(document).ready(function () {
    $.get("http://www.google.com", function (r) {
        window.alert(r);
    });
});

Solution

  • I believe that the inconsistency here is due to the fact that the first resource has an Access-Control-Allow-Origin: * header, so it supports CORS and allows scripts from all domains to access the data with AJAX and XMLHttpRequests.

    By contrast, google.com does not, so trying to access it from another domain will give you the usual errors.

    Adding that header to any page will circumvent the Same Origin Policy. You could also do Access-Control-Allow-Origin: domain to only allow requests from the domain domain.

    Take a look at this for more information on CORS support.