Angular 6 - “Service workers are disabled or not supported” error

蹲街弑〆低调 提交于 2020-07-15 11:41:04

问题


I want to push notification subscription with web-push module and angular service worker. I've followed instructions from these links: Angular Push Notifications: a Complete Step-by-Step Guide and Push Notifications with Angular & Express yet the notification prompt was not showing up as it should. I've checked the swPush object and found out that it was not enabled, and I don't know why even I've followed angular/pwa installation instructions exactly as those links said. Hope someone here can help. Thanks a lot!

I run the application with my own Nodejs server, not with http-server module.

Here is my push subcription code:

readonly VAPID_PUBLIC_KEY =
'BIfDkegCvhzctX06rYvwQImhbfAymWYE3wtcog9E4Zj7LOgX6TQFS6fZSqLCt01zBZtc1-jSwpZrZEmTQ2i95V8'; // key generated with web-push

 constructor(
   private user: UserService,
   private httpClient: HttpClient,
   private router: Router,
   private auth: AuthService,
   private swPush: SwPush
 ) {
     this.swPush.requestSubscription({
       serverPublicKey: this.VAPID_PUBLIC_KEY
     })
     .then(subcription => {
       console.log('Send ' + subcription + ' to server');
     })
     .catch(console.error);
}

Error returned:

Error: Service workers are disabled or not supported by this browser at SwPush.push../node_modules/@angular/service-worker/fesm5/service-worker.js.SwPush.requestSubscription (service-worker.js:146) at new DashboardComponent (dashboard.component.ts:40) at createClass (core.js:9311) at createDirectiveInstance (core.js:9186) at createViewNodes (core.js:10406) at createRootView (core.js:10320) at callWithDebugContext (core.js:11351) at Object.debugCreateRootView [as createRootView] (core.js:10838) at ComponentFactory_.push../node_modules/@angular/core/fesm5/core.js.ComponentFactory_.create (core.js:8666) at ComponentFactoryBoundToModule.push../node_modules/@angular/core/fesm5/core.js.ComponentFactoryBoundToModule.create (core.js:3315)

Expected result:


回答1:


This error was caused due to the reason that service workers don't work with ng serve. Run with http-server then it works fine. As in Angular service workers said:

Because ng serve does not work with service workers, you must use a separate HTTP server to test your project locally. You can use any HTTP server




回答2:


Just set the service worker to work in dev environment also in 'AppModule'

ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production})

To

ServiceWorkerModule.register('ngsw-worker.js', { enabled: true})


来源:https://stackoverflow.com/questions/52513466/angular-6-service-workers-are-disabled-or-not-supported-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!