I'm writing a web application in HTML/Javacript that records audio and uploads it to a server. Now, I would like to put it also in cache so it's available to service.workers for an offline scenario. What's the best way to do this?
Program flow:
If you are online, of course, all works well.
I would like to have the file locally available for listening before it is remotely saved, and backup it on server ASAP.
This is my routine:
function mettiincache(name, myBlob) {
var resp = new Response(myBlob)
var CACHE_NAME = 'window-cache-v1';
caches.open(CACHE_NAME).then(function (cache) {
cache.put(name, resp)
}).catch(function (error) {
ChromeSamples.setStatus(error);
});
}
When I look in Application/cache storage using Chrome DevTools, I find an entry with the correct path/name and content-Type, but with a content-Length of 0 bytes
Note that you might create / use a separate worker 'audioWorker.js' from the SW.js for running the apps audio cache because IMO its easier to test and the SW lifecycle is pretty involved and pretty oriented to its own app cache of 'real' urls used by the app.
Also note an inconsistency with allowable protocols used in the normal Service-Worker implementation that intercepts calls to 'fetch' - blob protocol used by the browser on your audio blobs will be rejected as invalid Urls by the browser.SW implementation. You cannot simply feed your blobs url to the normal SW lifecycle because its URL starts with 'blob://'.
The url from the audioBlob is fine if you choose NOT to use a SW for the cache. However, you might want to suffix it with a mimeType...
url = URL.createObjectURL(audio); // protocol of this is 'blob://'
wUrl = url +"?type=" + {$audio.blob.data.type};
console.log("SW CACH1 " +wUrl);
myCacheWorker.postMessage({ action: 'navigate', url: wUrl });
in the cacheWorker, onMessage , write to the cache:
onmessage = function( e ){
switch( e.data.action ){
case 'navigate':
upcache(e.data.url).then(() => {
postMessage({done: 'done'});
});
break;
}}
//boiler plate cache write below from any example
var upcache = function( url ){
return caches.open($cname)
.then((openCache) => {
return fetch(fetchUrl).then(function(resp) {
if (!resp.ok) {
throw new TypeError('Bad response status');
}
return openCache.put(url, resp);
})
});
}