nick bellavi
nick bellavi

Reputation: 67

Service worker fetch event not firing (Path issue)

So I'm trying to work with service worker in my angular web app to display a custom offline page, The problem I'm running into is

While trying to register the service worker file (service-worker.js) from the root directory ,getting the following error enter image description here

But if I put the service-worker.js file in assets folder it works as expected but the fetch wont fire since the service is in assets folder

enter image description here

My question would be if i have my file in the angular root folder how do import/give the correct path. so that the scope of the service worker is http://localhost:4200/

app.component.ts


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'service-worker';

  ngOnInit(): void{
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/assets/service-worker.js').then((reg)=>{
        console.log(reg);
      })
    }
  }
}

location of my service worker file in the below image

enter image description here

I'm new to angular so any guidance will be helpful ,thanks in advance

Upvotes: 0

Views: 369

Answers (1)

Andrei
Andrei

Reputation: 12021

there is a configuration section in angular.json called assets. this section describes what "static" files should be transfered to dist folder along with the application files. by default "src/favicon.ico" and "src/assets" should be there. also add path/to/service-worker.js. and it will reach the resulting built folder

Upvotes: 2

Related Questions