Canvas.Todataurl() Securityerror

canvas.toDataURL() SecurityError

Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:

Although you can use images without CORS approval in your canvas,
doing so taints the canvas. Once a canvas has been tainted, you can no
longer pull data back out of the canvas. For example, you can no
longer use the canvas toBlob(), toDataURL(), or getImageData()
methods; doing so will throw a security error.

This protects users from having private data exposed by using images
to pull information from remote web sites without permission.

I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!

EDIT:

As this answer is still the accepted answer, you should check out @shadyshrif's answer, which is to use:

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

This will only work if you have the correct permissions, but will at least allow you to do what you want.

SecurityError: The operation is insecure in canvas.toDataURL

It would be helpful if you could post the code you are using to modify the canvas before attempting to export it. With the information you provided, my guess would be that you are writing content from an external source to your canvas. This is why it was working before and is no longer working. I assume your initial tests used a resource from the same origin.



Explanation

The same security sandbox exists with the canvas as does with any data requests being made from your code. Anytime you load content from another domain/origin it will trigger the canvas to set the origin-clean flag to false. This means the browser will prevent you from exporting data that has been loaded into the canvas. There are quite a few posts pertaining to this type of issue on StackOverflow:

  • canvas.toDataURL() Security Error The operation is insecure
  • Security Error with canvas.toDataURL() and drawImage()

Why does canvas.toDataURL() throw a security exception?

In the specs it says:

Whenever the toDataURL() method of a
canvas element whose origin-clean flag
is set to false is called, the method
must raise a SECURITY_ERR exception.

If the image is coming from another server I don't think you can use toDataURL()



Related Topics



Leave a reply



Submit