Reputation: 1035
I am trying to cache images from the LastFM API. Now, the API response itself is cached fine and the page loads as expected, however, there are no images.
Looking into the developer console, I can see a couple of errors regarding the retrieval of the images and they're as follows:
Fetch API cannot load http://img2-ak.lst.fm/i/u/300x300/a32cb06bb22bc5d10654a5156fe78cf6.png. The parent document page has been unloaded.
I'm very new to service workers and this has got me tearing my hair out (no, not literally).
I've followed a couple of tutorials and this is the code I've got so far (irrelevant code has been stripped out).
var CACHE_NAME = 'WELFORDIAN-CACHE-V2';
var urlsToCache = [
'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=**USERNAME**&api_key=6136000ba0899c52db5ebcee77d4be15&format=json'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event) {
var reqURL = new URL(event.request.url);
if (/lst.fm/.test(reqURL)) {
event.respondWith(lastFMImageResponse(event.request));
} else {
event.respondWith(
caches.match(event.request).then(function(response) {
if (response) {
return response;
}
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(
function(response) {
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
var responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
}).catch(function(err) {
return err;
})
);
}
});
function lastFMImageResponse(request) {
return caches.match(request).then(function(response) {
if (response) {
return response;
}
return fetch(request).then(function(response) {
caches.open('lfm-images').then(function(cache) {
cache.put(request, response);
});
return response.clone();
});
});
}
I'm obviously doing something wrong, but can anyone with more experience than I explain what it is?
Upvotes: 2
Views: 2438
Reputation: 10782
The problem is that your website is HTTPS, while the images are served via HTTP.
Mixed content is currently not working well with service workers: https://github.com/w3c/webappsec/issues/415.
Upvotes: 2