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
Selected Reading
Is their a cross-origin attribute in HTML5?
Yes, HTML5 includes the crossorigin attribute. According to the official specification, it's defined as:
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.
Syntax
<img src="external-image.jpg" crossorigin="anonymous"> <script src="external-script.js" crossorigin="use-credentials"></script> <link rel="stylesheet" href="external-style.css" crossorigin>
Supported Values
The crossorigin attribute accepts two values:
| Value | Description | Credentials Sent? |
|---|---|---|
anonymous |
Performs CORS request without credentials | No |
use-credentials |
Performs CORS request with credentials | Yes |
Example: Canvas Image Access
<!DOCTYPE html>
<html>
<head>
<title>Cross-Origin Canvas Example</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<img id="myImage" src="https://via.placeholder.com/200" crossorigin="anonymous" style="display:none;">
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const image = document.getElementById('myImage');
image.onload = function() {
// Draw the cross-origin image to canvas
ctx.drawImage(image, 0, 0);
try {
// This works because of crossorigin="anonymous"
const imageData = canvas.toDataURL();
console.log('Successfully extracted image data');
} catch (error) {
console.log('Error accessing canvas data:', error.message);
}
};
</script>
</body>
</html>
Without crossorigin Attribute
Without the crossorigin attribute, accessing canvas data from cross-origin images throws a security error:
<canvas id="canvas"></canvas>
<img id="img" src="https://example.com/image.jpg">
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = document.getElementById('img');
img.onload = function() {
ctx.drawImage(img, 0, 0);
// This will throw: "Tainted canvases may not be exported"
try {
canvas.toDataURL();
} catch (error) {
console.log('Security Error:', error.message);
}
};
</script>
Supported Elements
The crossorigin attribute is supported on these HTML elements:
-
<img>- Images -
<script>- JavaScript files -
<link>- Stylesheets and other resources -
<audio>and<video>- Media elements
Conclusion
The crossorigin attribute enables secure access to cross-origin resources in HTML5. Use anonymous for basic CORS requests or use-credentials when authentication is required.
Advertisements
