Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use service workers in Cordova Android app?

After digging deep into this issue, I conclude that there is no support for Service workers in Android as it blocks service workers from HTTP or file protocols.

Also the support of Service worker in Ionic framework do not clearly state that it is not supported in hybrid mobile apps. It's kind of misleading too as in this case. Ionic's Service Worker support comes into picture only in case of Progressive Web App and not in hybrid mobile app as mentioned in their official blog

Adding to the above info, most of the functionality that can be achieved by using Service Workers are already available as part of plugins like push notification plugin which should be suffice in most cases.

The bottom line is that the Service Workers are not supported in Cordova Android as well as in Ionic framework. For more info, check out the following link


I couldn’t take “no” for an answer so went on a hunt to see if I could code my way out of this.

Note, I'm not sure I was having the same issue or even had the same req as the OP (apologies if not, but hopefully it was)... my scenario was this, for clarity I had initial luck with manually fetching and adding items (https://localhost/cordova.js and the plugin files) to the cache the Service Worker uses. I did this on first run up and the 2nd run up (even if offline) worked… so some good progress. Weirdly on subsequent run ups some (most) of the manually cached items were removed and so startups did not complete successfully.

I then looked into if I could bypass the SW completely for calls to localhost, and what do you know, it seems to work. Essentially in the SW’s fetch handler I have a conditional clause to do nothing if it spots localhost in the url. This has the affect that SW can’t find a fetch handler that takes care of the request and then the browser makes the call to fetch the asset just as if there were no SW at all.

I have tested this for both online/offline starts, and made sure I can access cordova and some of the plugins, and all seems to run just fine. Note, all testing so far is on Android.

An example of the code I used is as followa (left an explicit “do nothing” comment in for clarity);

 self.addEventListener('fetch', event => {
        console.log('Fetch event for ', event.request.url);
        if (event.request.url.includes("localhost")) {
            // Do Nothing
        } else {
        event.respondWith(
          caches.match(event.request, {
           // ... do the rest of the SW handling

I’d be interested to hear if other folk had tried this and then had any issues with it.