Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capacitor Service worker registration unknown error / network connection refused

I'm currently working on making a app with Capacitor because it uses an internal https server to serve files to the WebView instead of the file protocol, this should allow me to use service workers but sadly enough this seems not to be the case, even though to my understanding everything I'm trying to do is within the spec.

Main script code:

    navigator.serviceWorker.register('sw.js');

Service worker code:

    console.log("I'm a service worker");

What I get back

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

What I expect to get back:

I'm a service worker

On the other hand when i just try to fetch the service worker with the exact same request it works fine.

Code:

    fetch("https://localhost:4634/sw.js", {
        "credentials":"omit",
        "headers": {},
        "referrer":"https://localhost:4634/sw.js",
        "referrerPolicy":"no-referrer-when-downgrade",
        "body":null,
        "method":"GET",
        "mode":"cors"
    }).then(res => {
        return res.text();
    }).then(text => {
        console.log(text);
    });

What I should get back:

    console.log("I'm a service worker");

If anyone knows what i'm doing wrong or if this somehow still is out of spec, please let me know.

like image 459
T99Rots Avatar asked Jan 31 '26 04:01

T99Rots


1 Answers

Your error message suggests that register doesn't recognize 'sw.js' as an eligible type.

There are a couple things you could try.

  1. Use a path from the server root and add options explicitly:
ServiceWorkerContainer.register('/sw.js', {
  scope: '/',
  type: 'module',
  updateViaCache: 'none'
})
  1. Check the response headers for sw.js from your server. They should include:
Cache-Control: no-store
Content-Type: application/javascript
Service-Worker-Allowed: /

If Capacitor doesn't generate these headers then you may have to use a proxy server to handle sw.js, before passing the response to WebView.

like image 123
J Stach Avatar answered Feb 01 '26 20:02

J Stach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!