Why does canvas.toDataURL() throws a security exception? - GeeksforGeeks

02 Jun, 2020
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. 
Syntax: 
Canvas.toDataURL(type, encoderOptions);

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.
Javascript
function getBase64FromImageUrl(URL) {    var img = new Image();    img.src = URL;    img.onload = function () {          var canvas = document.createElement("canvas");        canvas.width = this.width;        canvas.height = this.height;          var ctx = canvas.getContext("2d");        ctx.drawImage(this, 0, 0);          var dataURL = canvas.toDataURL("image/png");           alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));      };}
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.

Solution for the above problem:  An image has an attribute known as crossorigin which is specified in HTML and by combining it with a suitable CORS header, it can be loaded from foreign origins to be used in the canvas behaving like belonging to the current origin. If The CORS approval is not taken, the canvas turns tainted, and there is no provision left to pull back data out of the canvas. Therefore methods like toBlob(), toDataURL(), or getImageData() cannot be used without throwing security errors. These errors can be prevented by setting the crossorigin attribute of the image using Javascript or HTML 
Example: 
HTML:
<img src="otherdomain.com"/>

JavaScript: 
  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.  
HTML-Misc
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to filter object array based on attributes?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript