- Attribute of
- <img> HTML Tag
- What does
- Indicates that CORS headers should be used in the HTTP request, and specifies whether or not to use credentials.
<img src="https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg" id="external-flamingo" crossorigin="anonymous">
Cross-origin images and the canvas element
What is the same-origin policy?
The same-origin policy is a browser security policy that restricts on-page scripts from accessing or posting data to resources from a different host, on a different port, or with a different protocol than the current page. This is a required browser security feature that helps prevent third-party applications from stealing end-user data. A
cross-origin resource, then, is a resource (file, document, image, script) which violates this policy by coming from a different host (domain) or by being accessed on a different port or with a different. Cross-origin resources are used all the time — hotlinked images, third-party libraries scripts like JQuery, resources served from Content Delivery Networks. These are all fine, because they are linked from the document source, and imported into the rendered document. The document itself can access cross-origin resources. However, scripts cannot access cross-origin resources. This is because a script could send data while accessing a cross-origin resource. (This policy does not stop scripts from all malicious behavior, but it ensures that user data will only be sent to resources controlled by the domain of the current page. If you, as a user, trust the domain, you can be sure your data isn't be sent to a nefarious third-party.)
<canvas> element and cross-origin resources
<canvas> element and, normally, read data out of one as well. However, if a cross-origin resource (such as a third-party script or a hot-linked image) is used to write information to a
<canvas>, then the
<canvas> becomes tainted. A tainted canvas can still be written to, but it cannot be read from. Attempts to read data back from a tainted canvas will result in a security error.
CORS and the
CORS, or Cross Origin Resource Sharing, is a method of accessing cross-origin resources safely. There are two parts to successful cross-origin resource sharing — proper resource headers from the server, and proper request headers from the client. To learn about adding CORS-enabled resource header, see this article about Server Side Access Control. Adding appropriate request headers for images is as simple as adding the
crossorigin attribute to the
<img> element. If your browser supports CORS, using the
crossorigin attribute (with any value) will generate the appropriate request headers.
Browser Support for crossorigin