Capacitor: Connection refused when call ngsw-worker.js file and Service worker is not registering

Created on 12 Jun 2019  ·  6Comments  ·  Source: ionic-team/capacitor

I can't register service worker in capacitor webview
I used angular and capacitor 1.0.0-beta.24

I think that URL schema need to be https which service worker required, How to make this https ? or what is the suitable solution to register SW
My package.json is :

image

and the problem is : (_This is from Android Emulator_)

Failed to load resource: net::ERR_CONNECTION_REFUSED
Uncaught Error: Uncaught (in promise): TypeError: Failed to register a ServiceWorker: An unknown error occurred when fetching the script.
TypeError: Failed to register a ServiceWorker: An unknown error occurred when fetching the script.

image

workaround

Most helpful comment

So, the problem is the web worker requests don't go through the regular shouldInterceptRequest.

You can use this workaround
https://stackoverflow.com/questions/55894716/how-to-package-a-hosted-web-app-with-ionic-capacitor

You don't need a plugin, you can use a similar code in the 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

All 6 comments

What are you doing with the service workers?
Can you provide a sample app?

Thanks @jcesarmobile for your reply
I created a PWA app that uses service worker for caching some requests and offline support. This work nice in web but not sure how this PWA app should work well inside the capacitor due to this issue.

So, can you provide a sample app?

I create a sample app in this repository
https://github.com/minajacob/capacitor-sw

Is there any news about the matter? I am having the same issue

So, the problem is the web worker requests don't go through the regular shouldInterceptRequest.

You can use this workaround
https://stackoverflow.com/questions/55894716/how-to-package-a-hosted-web-app-with-ionic-capacitor

You don't need a plugin, you can use a similar code in the 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

Was this page helpful?
0 / 5 - 0 ratings