crossorigin

The crossorigin attribute in HTML manages how browsers handle cross-origin requests for resources like images or scripts, affecting their privacy and security settings.

crossorigin attribute

The crossorigin attribute can be applied to elements such as <audio>, <img>, <link>, <script>, and <video>. It manages Cross-Origin Resource Sharing (CORS) requests.

  • anonymous: Initiates CORS requests without sending credentials.
  • use-credentials: Initiates CORS requests with credentials included.
  • Empty (""): Defaults to the anonymous setting.
  • Not set: CORS is disabled, enforcing cross-origin restrictions.

Syntax

index.html
<script crossorigin="anonymous|use-credentials">
The crossorigin attribute does not work with rel="icon" in browsers based on Chromium.

Example

index.html
<script
  src="https://example.com/example-framework.js"
  crossorigin="anonymous">
</script>
This script is fetched without sending user credentials.

Web Manifest with Credentials

When retrieving a manifest that requires authentication, the use-credentials value should be applied, even if the file originates from the same domain.

index.html
<link rel="manifest" href="/app.webmanifest" crossorigin="use-credentials" />

Attribute Values

ValueDescription
anonymousSends a cross-origin request without credentials (cookies, certificates, HTTP authentication).
use-credentialsSends a cross-origin request with credentials included, such as cookies or authentication data.

Use cases

  • Security: Controls whether credentials are included in cross-origin requests.
  • Caching: Resources can be cached if crossorigin="anonymous" and the server allows it.
  • Error Reporting: Ensures proper error handling when CORS issues occur.

See also

  • Cross-Origin Resource Sharing (CORS)
  • HTML attribute

Conclusion

The crossorigin attribute is crucial for managing cross-origin requests in HTML, influencing security, caching, and error handling. By specifying whether credentials are included in requests, developers can ensure secure and efficient resource fetching. Proper use of this attribute enhances performance and prevents unnecessary CORS-related issues when working with external resources.