Skip to content
Advertisement

Is it okay to mark image.crossOrigin as “anonymous” even when it is not?

When using cross origin urls for images with the canvas api, if the image is cross origin I am getting a tainted canvas exception. MDN Allowing cross-origin use of images and canvas.

Changing crossOrigin="anonymous" fixes the issue; however, is it okay to always do that? Or should I check the url first to make sure that it really is crossOrigin before setting it to anonymous?

e.g.

function isCrossOriginURL(url) {
  const { location } = window;
  const parts = url.match(/^(w+:)//([^:/?#]*):?(d*)/i);

  return (
    parts !== null &&
    (parts[1] !== location.protocol ||
      parts[2] !== location.hostname ||
      parts[3] !== location.port)
  );
}

console.log(isCrossOriginURL("https://stacksnippets.net"))
console.log(isCrossOriginURL("https://google.com"))

Advertisement

Answer

Is is not OK to always set crossorigin=anonymous.

The crossorigin attribute is a statement that you want to do something to the image which requires permission using CORS.

If the server doesn’t grant permission using CORS then you won’t be able to do things with the image that normally don’t require permission … such as displaying the image at all.

<img src="https://placem.at/places?h=100&w=100" alt="No CORS needed">

<img src="https://placem.at/places?h=100&w=100" crossorigin=anonymous alt="Requires CORS">
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement