Purpose of the crossorigin attribute...?

In both image and script tags.

My understanding was that you can access both scripts and images on other domains. So when does one use this attribute?

Is this when you want to restrict the ability of others to access your scripts and image?

Images:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-crossorigin

Scripts:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script


Solution 1:

The answer can be found in the specification.

For img:

The crossorigin attribute is a CORS settings attribute. Its purpose is to allow images from third-party sites that allow cross-origin access to be used with canvas.

and for script:

The crossorigin attribute is a CORS settings attribute. It controls, for scripts that are obtained from other origins, whether error information will be exposed.

Solution 2:

This is how we have successfully used crossorigin attribute it in a script tag:

Problem we had: We were trying to log js errors in the server using window.onerror

Almost all of the errors that we were logging had this message : Script error. and we were getting very little information about how to solve these js errors.

It turns out that the native implementation in chrome to report errors

if (securityOrigin()->canRequest(targetUrl)) {
        message = errorMessage;
        line = lineNumber;
        sourceName = sourceURL;
} else {
        message = "Script error.";
        sourceName = String();
        line = 0;
}

will send message as Script error. if the requested static asset violates the browser's same-origin policy.

In our case we were serving the static asset from a cdn.

The way we solved it was adding the crossorigin attribute to the script tag.

P.S. Got all the info from this answer