Search code examples
javascriptsecuritysame-origin-policywebsecurity

Same Origin Policy: Why can't JS code make an HTTP request to its domain?


Example

I have a site http://example.com. This site uses a third-party JS code: <script src="http://third.party/script.js"></script>

The http://third.party/script.js contains the following code:

console.log("self.origin", self.origin);
fetch("http://third.party/api");

When I open http://example.com, I get the following output in dev console:

self.origin http://example.com

Access to fetch at 'http://third.party/api' from origin 'http://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The third party script tried to load data from the third-party API, but it failed. Why did it fail?

The third party script and API have the same domain name (origin). Should it be allowed by Same Origin Policy?


Solution

  • The origin is determined by the URL of the webpage the JavaScript is loaded into, not the URL of the JS file itself.