Fix CORS issue when fetching cover art for downloads

This commit is contained in:
Julien Maille 2025-12-26 00:47:11 +01:00 committed by Julien Maille
parent e0cfaba14c
commit 64e4c0f43c
2 changed files with 30 additions and 2 deletions

View file

@ -13,16 +13,41 @@ async function getCoverBlob(api, coverId) {
if (!coverId) return null;
if (coverCache.has(coverId)) return coverCache.get(coverId);
const fetchWithProxy = async (url) => {
try {
const proxyUrl = `https://corsproxy.io/?${encodeURIComponent(url)}`;
const response = await fetch(proxyUrl);
if (response.ok) return await response.blob();
} catch (e) {
console.warn('Proxy fetch failed:', e);
}
return null;
};
try {
const url = api.getCoverUrl(coverId, '1280');
// Try direct fetch first
const response = await fetch(url);
if (response.ok) {
const blob = await response.blob();
coverCache.set(coverId, blob);
return blob;
} else {
// If direct fetch fails (e.g. 404 from SW due to CORS), try proxy
const blob = await fetchWithProxy(url);
if (blob) {
coverCache.set(coverId, blob);
return blob;
}
}
} catch (e) {
// Network error (CORS rejection not handled by SW), try proxy
const url = api.getCoverUrl(coverId, '1280');
const blob = await fetchWithProxy(url);
if (blob) {
coverCache.set(coverId, blob);
return blob;
}
} catch (error) {
console.warn('Cover fetch failed:', error);
}
return null;
}

3
sw.js
View file

@ -45,6 +45,9 @@ self.addEventListener('fetch', event => {
cache.put(event.request, networkResponse.clone());
}
return networkResponse;
}).catch(() => {
// If fetch fails (e.g. CORS), return null/error so client handles it
return new Response(null, { status: 404, statusText: 'Image fetch failed' });
});
});
})