SECURITY_ERR: DOM Exception 18 when invoking toDat

2019-04-22 23:48发布

问题:

I am getting the following error while trying to retrieve the data URL from a canvas on which an SVG image is drawn on Internet Explorer and Safari browsers while the others are working properly.

In addition, the SVG image contains some <image> elements whose xlink:href attributes are set to images read from the user's file system as data URLs. Since these images are not located on different domains, i could not think of any reason why this error is thrown when trying to get the dataURL of the canvas on which the SVG image is drawn. Thanks in advance.

SECURITY_ERR: DOM Exception 18: An attempt was made to break through the security policy of the user agent."

回答1:

I can confirm this issue in Internet Explorer 11 using a test case that I made:
http://jsfiddle.net/tsbXW/

This is a known limitation of Internet Explorer that Microsoft is working on:
https://connect.microsoft.com/IE/feedback/details/828416/cavas-todataurl-method-doesnt-work-after-draw-svg-file-to-canvas

As demonstrated by the bug report, any SVG image drawn into a canvas taints the canvas, causing a SecurityError when toDataURL() is called.

For what it's worth, the bug report's test case does not work in Safari 7.0.5, either (though purportedly Apple has fixed the issue in Safari 8). Also, the test case does not work in Firefox until version 11 due to Bug 672013 - Allow SVG-as-an-image to be drawn into a canvas without marking it as write-only.



回答2:

It seems that your SVGs are breaking the security policy, even though they shouldn't.

A possible solution would be to use canvg, which parses SVG and renders to canvas directly.

If you have the SVG text, canvg adds a drawSvg method that works just like drawImage. Sample:

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);