简体   繁体   中英

Service Worker not being register in Angular

I want to do a push notification to my Angular app. I'm doing it with vanilla js and not with the Angular service worker or @angular/pwa.

I added the path of the js file in the script option in angular.json. When the service worker is going to be register it redirects the path from the root ( http://127.0.0.1:8887/sw.js ) and not from the folder that I place the file in.

This is the angular.json file:

    "scripts": [
      "./src/assets/js/main.js",
      "./src/assets/js/sw.js"
    ]

main.js file:

const applicationServerPublicKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

let isSubscribed = false;
let swRegistration = null;

if ('serviceWorker' in navigator && 'PushManager' in window) {
    console.log('Service Worker and Push is supported');

    navigator.serviceWorker.register('/sw.js')  // I tried ./sw.js and also /src/assets/js/sw.js and sw.js alone
    .then(function(swReg) {
      console.log('Service Worker is registered', swReg);

      swRegistration = swReg;
    })
    .catch(function(error) {
      console.error('Service Worker Error', error);
    });
  } else {
    console.warn('Push messaging is not supported');
    pushButton.textContent = 'Push Not Supported';
  }

service worker file just for testing that the file is reachable by the moment:

console.log('sw');

this is the error:

Service Worker Error TypeError: Failed to register a ServiceWorker for scope ('http://127.0.0.1:8887/') with script ('http://127.0.0.1:8887/sw.js'): A bad HTTP response code (404) was received when fetching the script.

The issue was resolve, I had to add the path /assets/js/sw.js to the navigator.serviceWorker.register('/assets/js/sw.js')

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