Search code examples
jqueryajaxsame-origin-policy

Who can exclude Same origin policy?


Code. Why

$.ajax({
    type : "get",
    url : "http://www.facebook.com",        
    success: function(data){
           console.log(data);
     }
});

works and

$.ajax({
    type : "get",
    url : "http://www.google.com",        
    success: function(data){
           console.log(data);
     }
});

throw the famous XMLHttpRequest cannot load Same origin policy exception on the browser console!

Why? I guess it depends by the browser?


Solution

  • http://www.facebook.com sends a 301 Moved Permanently response, which redirects to https://www.facebook.com.

    It appears that the redirect causes the request to fail more quietly than an outright cross-domain failure. However, both requests do fail.

    EDIT

    According to the W3C Ajax specification:

    If the response has an HTTP status code of 301, 302, 303, 307, or 308 ...

    1. Set the request URL to the URL conveyed by the Location header.
    2. If the source origin and the origin of request URL are same origin transparently follow the redirect while observing the same-origin request event rules.
    3. Otherwise, follow the cross-origin request steps and terminate the steps for this algorithm.

    The text "transparently follow the redirect" means that Ajax should treat the target of 301 redirects as the original target. However, when performing a redirect, the same-origin policy is re-checked against the new target origin.

    The target domain must also have the same origin as the requesting script, or it must respond with CORS headers that allow access by the requesting origin.