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)
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
}