vue.jsprogressive-web-appscapacitorvue-pwa

Failed to register a ServiceWorker for scope ('http://localhost/') with script ('http://localhost/service-worker.js')


I am trying to convert my vue pwa project to a android project with capacitor.

Here are the steps i followed.

First added pwa to my vue project and build it

vue add @vue/pwa
npm run build

At this point the app works as a pwa, having serviceworker and offline support. Then I added capacitor and converted to android project

npm install --save @capacitor/core @capacitor/cli
npx cap init 
npx cap add android
npm run build
npx cap copy
npx cap open android

But when I run the android project i get the following errors

E/Capacitor/Console: File: http://localhost/js/chunk-vendors.3815e007.js - Line 7 - Msg: TypeError: Cannot read property '-1' of undefined
I/chromium: [INFO:CONSOLE(0)] "An unknown error occurred when fetching the script.", source:  (0)
E/Capacitor/Console: File: http://localhost/js/app.15b911b2.js - Line 1 - Msg: Error during service worker registration: TypeError: Failed to register a ServiceWorker for scope ('http://localhost/') with script ('http://localhost/service-worker.js'): An unknown error occurred when fetching the script.
D/Capacitor: App paused

Here is the console log I need to properly work serviceworker

EDIT: When i clicked http://localhost/js/app.15b911b2.js i found NOT FOUND. But if i add port to the link - http://localhost:8081/js/app.15b911b2.js I can fetch the file. So im guessing if could make my project use the link with port the problem will be solved.


Solution

  • Service workers won’t go through the capacitor requests so they fail to load. You can add this code in MainActivity.java like this:

    if(Build.VERSION.SDK_INT >= 24 ){
      ServiceWorkerController swController = ServiceWorkerController.getInstance();
    
      swController.setServiceWorkerClient(new ServiceWorkerClient() {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
          return bridge.getLocalServer().shouldInterceptRequest(request);
        }
      });
    }
    

    But notice that it requires SDK 24 and Capacitor supports SDK 21, so it won't work on 21-23