JavaScript – canvas.toBlob() SecurityError: The Operation is Insecure

javascriptopenlayers

I'm trying to get the image of Map from OpenLayers 4.6.5 and the following error is appearing each and every time.

I'm using cdn link of OpenLayers 4.6.5 for the base Map in JavaScript with Apache Tomcat server in web application (HTTP format) everything is working fine.

But when I start to get the image from OpenLayers Map
it's giving :

SecurityError: The operation is insecure.

in case of FireFox and

Uncaught DOMException: Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.

It's really head eating and I have tried many ways
like CORS, timeout and anything available from other sources:

   canvas.toBlob(function(blob)
            {  

             var imgData = new Image();
             imgData.setAttribute('crossOrigin', 'anonymous');
             imgData.src = canvas.toDataURL('png');
           }

I found out something like (I'm not sure) : it's due to security of the network i.e I'm using secure cdn link from OpenLayers :

https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.5/ol.js

which is https:// and my application is http:// —- is this a problem? I'm really tired of this.

Could anyone look into it?

Best Answer

Tainted canvas happens, when you load some CORS insecure third-party (cross-domain) image into your map (canvas). It is not related to scripts or timeouts. It is a security behavior from your browser, which disable downloading of the tainted image (possible security threat). Check all your map sources, to avoid having tainted canvas the source must be CORS compliant. If the source is not on your domain, it must have access-control-allow-origin header set to your domain or to *. Also your source should have parameter crossOrigin set to Anonymous for example like this:

source: new ol.source.TileWMS({
            crossOrigin: "anonymous",...

More information here and here: