Why does canvas.toDataURL() throws a security exception?
Canvas.toDataURL(): The canvas.toDataURL() method returns the URI(Uniform Resource Identifier) of the web resource. It consists of an image depicted in the format specified by the type parameter whose default value is PNG.
- type: It is an optional attribute that contains DOMString commenting about the image format. Its default value is PNG.
- encoderOptions : It consists of a numeric value between 0 and 1 used to indicate the quality of the image to be used for the various image formats. Its default value is 0.92.
Security Exceptions: The security exceptions are thrown if the canvas element is not origin clean i.e. if its origin-clean flag is not set. (False). In other words, if the canvas element consists of foreign content then the security is on stake and SECURITY_ERR exception occurs. The moment the canvas is used for drawing data not following the rules related to the origin and without using the CORS (Cross-origin resource sharing) mechanism, it becomes tainted. Tainted canvas is not considered secure. Trials to retrieve image data from the canvas will lead to failure indicated by security exceptions. Along with toDataURL(), calling methods such as toBlob() and getImageData() will also lead to similar kinds of errors.
These exceptions are used to safeguard the users from getting their private data being exposed without their prior permission. Since images can be used to capture information from websites, the use of exceptions is a must.
Example: Canvas element producing the exception.
Output: These kinds of security errors occur when a trial is made to manipulate an image on canvas that is not authorized to be handled in the code. These errors are caused by the Access-Control-Allow-Origin header of a request, which the server has approved. Since the image belongs to another domain, most browsers show abnormalities in accessing them leading to a major security breach.
Uncaught Security Error: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: tainted canvases may not be exported.
var image = new Image(); image.crossOrigin = "Anonymous"; ...
Note: this approach can work only when the server response has the following Access-Control-Allow-Origin header on it. Otherwise, the image from origin ‘otherdomain.com’ will get blocked from being loaded by the Cross-Origin Resource Sharing policy.
Since the problem is that image does not belong to the current domain, a proxy with the server language can be created similar to displaying HTTP contents on HTTPS contents providing it a secure environment.