Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the usage of the cross-origin attribute in HTML5?
The crossorigin attribute in HTML5 is a CORS (Cross-Origin Resource Sharing) settings attribute. It controls how the browser handles cross-origin requests when loading resources like images, scripts, and stylesheets from third-party domains.
As the official specification states −
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.
Why Is the crossorigin Attribute Needed?
By default, when you load an image from a foreign origin and draw it onto an HTML5 <canvas>, the canvas becomes tainted. A tainted canvas cannot be read back using methods like toDataURL() or getImageData() − the browser blocks this to prevent leaking sensitive data from other domains.
When the crossorigin attribute is combined with the proper CORS headers on the server, it allows images loaded from foreign origins to be used in canvas as if they were loaded from the current origin.
Attribute Values
The crossorigin attribute accepts two values −
-
anonymous− A CORS request is sent without credentials (cookies or HTTP authentication). -
use-credentials− A CORS request is sent with credentials included.
Example: Using crossorigin with an Image
<!-- Load a cross-origin image for use in canvas -->
<img src="https://example.com/photo.jpg"
crossorigin="anonymous"
alt="Cross-origin image" />
Example: Using crossorigin with a Script
The crossorigin attribute is also useful on <script> tags. Without it, if a script loaded from a third-party CDN throws an error, the browser only reports a generic "Script error" message with no details. With crossorigin set, the browser provides the full error message, source URL, and line number −
<script src="https://cdn.example.com/app.js"
crossorigin="anonymous">
</script>
Internally, the browser decides how much error detail to expose based on the origin of the script ?
// Browser's internal logic for cross-origin error reporting
if (securityOrigin().canRequest(targetUrl)) {
msg = myError;
line = myLineNumber;
source = sourceURL;
} else {
msg = "Error!";
source = "";
line = 0;
}
When the CORS check passes (same origin or valid crossorigin attribute with proper server headers), the full error details (myError, myLineNumber, sourceURL) are available. Otherwise, the browser returns a generic "Error!" with no useful information.
Conclusion
The crossorigin attribute enables safe cross-origin resource loading in HTML5. Use it on <img> tags to allow canvas operations on foreign images, and on <script> tags to get detailed error reporting from third-party scripts. The server must also send the appropriate Access-Control-Allow-Origin header for it to work.
