0
votes

I am trying to implement FCM chrome client on Eclipse IDE.

Using Javascript, I am trying to register the default service worker : firebase-messaging-sw.js but the path for this js file cannot be resolved by project.

The SDK is searching for this file at hosting level: /firebase-messaging-sw.js i.e. https://localhost:8080/firebase-messaging-sw.js but not at https://localhost:8080/myapp/firebase-messaging-sw.js

Therefore, I get Error : Firebase Service worker not found while using GWT (404 Error)

How can I resolve this issue ?

1

1 Answers

0
votes

Service workers by default should reside on the root of the application. To register a service worker st some other location than the default location, you can use the following code.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/sw-test/'})
  .then(function(reg) {
    // registration worked
    console.log('Registration succeeded. Scope is ' + reg.scope);
  }).catch(function(error) {
    // registration failed
    console.log('Registration failed with ' + error);
  });
}

From MDN,

  1. The outer block performs a feature detection test to make sure service workers are supported before trying to register one.
  2. Next, we use the ServiceWorkerContainer.register() function to register the service worker for this site, which is just a JavaScript file residing inside our app (note this is the file's URL relative to the origin, not the JS file that references it.)
  3. The scope parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In this case, we have specified '/sw-test/', which means all content under the app's origin. If you leave it out, it will default to this value anyway, but we specified it here for illustration purposes.
  4. The .then() promise function is used to chain a success case onto our promise structure. When the promise resolves successfully, the code inside it executes.
  5. Finally, we chain a .catch() function onto the end that will run if the promise is rejected.

This registers a service worker, which runs in a worker context, and therefore has no DOM access. You then run code in the service worker outside of your normal pages to control their loading.