-1

I'm working on an extension, that when clicked will get the URL of the thumbnail of an element, and then it needs to generate a Base64 String from it. I've this code:

async function urlToBase64(url) {
    const response = await fetch(url, { mode: 'no-cors' });
    const blob = await response.blob();

    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
            const base64String = reader.result;
            console.log(base64String);
            resolve(base64String);
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
    });
}

const base64String = await urlToBase64(thumb); //<- This is inside an Async block

But when I print the value of base64String, it only gives "data:application/octet-stream;base64,", as if the content had been empty, but on the Network tab I can see that the Img got received(Although what I think is weird is that it doesn't have return code)

Image

Is there something that I'm forgetting to do for this to work? BTW if you wonder why I'm not using canvas, is because this site, for some reason, seems to require the image to be called with no-cors mode, or else causes an error, for example, this code gives me CORS issues

const getImg64 = async(source) => {
  const convertImgToBase64URL = (url) => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onload = () => {
          let canvas = document.createElement('CANVAS')
          const ctx = canvas.getContext('2d')
          canvas.height = img.height;
          canvas.width = img.width;
          ctx.drawImage(img, 0, 0);
          const dataURL = canvas.toDataURL();
          canvas = null;
          resolve(dataURL)
      }
      img.src = url;
    })
  }
  //for the demonstration purposes I used proxy server to avoid cross origin error
  const image = await convertImgToBase64URL(source)
  return image
}
Efraín
  • 453
  • 1
  • 7
  • 13

1 Answers1

-1

Opaque responses

Try logging the value of response.type immediately after setting const response.

A value of "opaque" would indicates blob data is restricted and attempts to access it will be unsuccessful. Per the note for the response.blob() method on MDM:

If the Response has a Response.type of "opaque", the resulting Blob will have a Blob.size of 0 and a Blob.type of empty string "", which renders it useless for methods like URL.createObjectURL

The emphasis on "like" is mine: if the resonse type is opaque I would assume you will not be able to access the data returned by the "no-cors" fetch request by any alternative means either.

traktor
  • 17,588
  • 4
  • 32
  • 53