Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...