简体   繁体   中英

Service worker is working even the code is Correct in Aurelia

I need a sample example of the service worker in Aurelia. I tried multiple code examples but no one was invoking the install, activate and fetch methods.

The service worker gets activated, but never got to the point where install is working or activated.

I need some help to understand the main issue. Also I noticed that addEventListener "load" to the window is not responding therefore I used "aurelia-composed".

service-worker.js

// installing & Activating & fetching 

    self.addEventListener("install", event => {
      console.log("====> service worker is installed ", event);

        })
      );
    });

    self.addEventListener("activate", event => {
      console.log(" ====> service worker is activated", event);
    });
    self.addEventListener("fetch", event => {
      console.log("====> service worker is fetched ", event);
    });

index.ejs

// placing the service worker in HTML

    <script>

        if (navigator.serviceWorker) {
          console.log("<== service worker supported ==>");

          window.addEventListener("aurelia-composed", () => {
            console.log("#### window loaded ######");
            navigator.serviceWorker
              .register("./service-worker.js")
              .then(reg => {
                console.log(" ++++  SW registered +++++++",reg);
              })
              .catch(err => {
                console.log(` error in registering worker`,err);    

              });
          });
        }
      </script>

there are two things I can observe for this issue: 1) Make sure the service-worker.js is outside the 'src' folder (where aurelia scans code). The service worker code must be a plain js file and must not be bundled. Also, there is a potential syntax error in the service-worker.js file. Attached goes my own version:

self.addEventListener("install", event => {
  console.log("====> service worker is installed ", event);

});

self.addEventListener("activate", event => {
  console.log(" ====> service worker is activated", event);
});

self.addEventListener("fetch", event => {
  console.log("====> service worker is fetched ", event);
});

2) The loading of the service worker file can be put at the end of the main.ts or main.js aurelia file, after the app is run:

    await aurelia.start();
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/sw.js')
        .then(function (registration) { return registration.update(); })
        .catch(console.error);
    }
    return aurelia.setRoot('app');

After doing all this, in my chrome console:

在此输入图像描述

And voilá!

Best regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM