-1

Suppose if my domain is A and I want to display an image from domain B I can do this successfully by placing the image URL from B in the src attribute of the img tag on my website and expect the picture to display. However when I try to display the image on a canvas and convert it to base64 using the toDataUrl function I am unable to do so due to CORS reasons.

My questions are - How come I get to display the image from domain B if it does allow cross origin resource sharing? Is it only a HTTP header setting on domain B that must be configured in order to allow my domain A to access the resource or is there a setting on domain A that needs to be activated as well?

Ikim SS
  • 139
  • 2
  • 8

2 Answers2

2

CORS doesn't place any restrictions. The Same Origin Policy places restrictions. CORS can remove some of them.

There is no restriction on displaying images.

<img alt="" src="//cross-origin.example.com/foo.jpeg"> is absolutely fine (although the site could attempt to defeat that by testing the referer header with server side code).

By default, JavaScript is prevented from accessing the data inside the image (e.g. placing the image on a <canvas> and then generating a data: URL from it which the JavaScript could then pass on to the server).

CORS can lift that restriction with an Access-Control-Allow-Origin header.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • ```+1``` just for that first paragraph. :-) But you might want to address the question about headers, etc. – T.J. Crowder Mar 23 '20 at 09:28
  • So basically the server at domain B has to send the Access-Control-Allow-Origin header in its reply? – Ikim SS Mar 23 '20 at 19:08
  • @IkimSS — Not for Site A to simply display the image, no. That's allowed automatically. See https://stackoverflow.com/a/35553666/19068 for an overview of how CORS works. – Quentin Mar 23 '20 at 21:00
0

Is it only a HTTP header setting on domain B that must be configured in order to allow my domain A to access the resource...

Yes, to indicate to the browser that it's safe for the origin domain B gives permission to to use the image, for instance:

Access-Control-Allow-Origin: https://domaina.example

Depending on how the image is being retrieved, it may need further headers to allow credentials or headers, but that's the main one.

Domain A doesn't need anything special, just code using the image data.

Full details in the specification.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875