Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With <script crossorigin='anonymous'>, why is a script "blocked by CORS policy"?

With Google Chrome or Firefox, if I try to load the following HTML:

<script crossorigin='anonymous' src='https://stackoverflow.com/foo.js'></script> 

I get a CORS error like this:

Access to Script at 'https://stackoverflow.com/foo.js' from origin 'https://stackoverflow.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource...

However, the same tag without the crossorigin='anonymous' attribute works fine (of course generating a 404 error, since foo.js does not exist).

This is surprising, since anonymous is just supposed to prevent sending any credentials, and script tags are not supposed to require CORS. What is causing this, and what should I do?

like image 234
pdg137 Avatar asked Dec 09 '16 21:12

pdg137


People also ask

What is crossorigin anonymous in script tag?

Attribute Values Specifies the mode of the CORS request: anonymous - A cross-origin request is performed. No credentials are sent. use-credentials - A cross-origin request is performed. Credentials are sent (e.g. a cookie, a certificate, a HTTP Basic authentication)

How do you fix crossorigin?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.

How do I stop CORS error in HTML?

In order to fix CORS, you need to make sure that the API is sending proper headers (Access-Control-Allow-*). That's why it's not something you can fix in the UI, and that's why it only causes an issue in the browser and not via curl: because it's the browser that checks and eventually blocks the calls.

What is crossorigin in link tag?

The HTML crossorigin Attribute in <link> element is used to specifying that supports the HTTP CORS request when fetching or loading the stylesheet or icon files from the third-party server. Syntax: <link crossorigin="anonymous | use-credentials"> Attribute Values: anonymous: It has a default value.


1 Answers

I was confused about this for a while. Here's how I now understand it:

According to the W3C, there are actually three possible values for the crossorigin attribute: anonymous, use-credentials, and an "missing value default" that can only be accessed by omitting the attribute. (An empty string, on the other hand, maps to anonymous.) The default value causes the browser to skip CORS entirely, which is the normal behavior I was expecting.

The crossorigin attribute should only be used if we care about getting error information for the script being loaded. Since accessing this information requires a CORS check, the Access-Control-Allow-Origin header must be present on the resource for it to be loaded.

like image 142
pdg137 Avatar answered Sep 25 '22 22:09

pdg137