Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Cross-Origin headers to allow Data URLs?

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?

like image 938
MidnightLightning Avatar asked Feb 21 '14 22:02

MidnightLightning


People also ask

How do you set allow cross-origin?

Simply add a header to your HttpServletResponse by calling addHeader : response. addHeader("Access-Control-Allow-Origin", "*");

How do I allow CORS 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.

What is cross-origin URL?

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.

Can Origin header be set?

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.


1 Answers

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'}));
like image 132
cuixiping Avatar answered Sep 20 '22 16:09

cuixiping