Internet Explorer canvas.toDataURL SecurityError

504 views Asked by At

I run the following code on Internet Explorer, it throws a SecurityError on the line var canvasDataUrl = canvas.toDataURL();

var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
var img = new Image;
img.onload = function(){
  canvasContext.drawImage(img,0,0);
  var canvasDataUrl = canvas.toDataURL(); // error occurs here
  console.log(canvasDataUrl);
};
img.src = 'https://via.placeholder.com/300x300';

What is the cause of that error, and how can I fix this ?

2

There are 2 answers

0
mr. pc_coder On BEST ANSWER

can you try crossOrigin

var img = new Image();
img.crossOrigin = "anonymous";

var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
var image = new Image();
image.crossOrigin = "anonymous"; 
image.onload = function (event) {
    try {
        canvasContext.drawImage(image, 0, 0, 200, 200);
        console.log(canvas.toDataURL());        
    } catch (e) {
        console.log(e);
    }
};
image.src = "https://i.chzbgr.com/maxW500/1691290368/h07F7F378/"

0
ntson9p On

The answer from @pc_coder is correct, and I want to provide some information about this error, you can see here https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

Because the pixels in a canvas's bitmap can come from a variety of sources, including images or videos retrieved from other hosts, it's inevitable that security problems may arise.

As soon as you draw into a canvas any data that was loaded from another origin without CORS approval, the canvas becomes tainted. A tainted canvas is one which is no longer considered secure, and any attempts to retrieve image data back from the canvas will cause an exception to be thrown.

If the source of the foreign content is an HTML or SVG element, attempting to retrieve the contents of the canvas isn't allowed.

If the foreign content comes from an image obtained from either as HTMLCanvasElement or ImageBitMap, and the image source doesn't meet the same origin rules, attempts to read the canvas's contents are blocked.

Calling any of the following on a tainted canvas will result in an error:

  • Calling getImageData() on the canvas's context
  • Calling toBlob() on the element itself
  • Calling toDataURL() on the canvas

Attempting any of these when the canvas is tainted will cause a SecurityError to be thrown. This protects users from having private data exposed by using images to pull information from remote web sites without permission.