I've got a javascript script that takes a SVG string and tries to put it on a canvas (to rasterize it). This works well in Chrome and Firefox, but Safari throws an error:
var img = new Image();
img.onload(function() {
context.drawImage(img, 0,0);
exportImage.src = canvas.toDataURL('image/png');
});
img.src="data:image/svg+xml;utf8,<svg>...</svg>";
When done this way, Safari throws an error at the toDataURL()
call:
SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.
if I add a img.crossOrigin=''
to the img
object before setting its src
, I instead get a Cross-origin image load denied by Cross-Origin Resource Sharing policy.
error. I have the following in my .htaccess
file for this site:
Header set Access-Control-Allow-Origin "*"
But as this is a data:
URL, this is not being queried? How do I properly set a Cross-Origin Resource Sharing header for scripts like this that are creating their own data:
URLs?
Simply add a header to your HttpServletResponse by calling addHeader : response. addHeader("Access-Control-Allow-Origin", "*");
Simply activate the add-on and perform the request. CORS or Cross-Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs). Installing this add-on will allow you to unblock this feature.
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
In short: you cannot. As described on MDN; Origin is a 'forbidden' header, meaning that you cannot change it programatically. You would need to configure the web server to allow CORS requests.
You can use blobURL instead of dataURL
. blobURL has no cross-origin issue currently.
see Blob and objectURL.
var img = new Image();
img.onload(function() {
context.drawImage(img, 0,0);
exportImage.src = canvas.toDataURL('image/png');
});
img.src=URL.createObjectURL(new Blob(['<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect x="0" y="0" height="100" width="100" fill="#00f"/></svg>'], {type : 'image/svg+xml'}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With