title: Can I run Firebase Cloud Messaging entirely in a web service worker?
body: <p><strong>TLDR:</strong> Is it a problem if you don't have FCM code running in the foreground of the application? Are there any problems that may arise from having everything in a web worker?</p>
  
  <hr>
  
  <p>I have the following service worker:</p>
  
  <pre><code>importScripts('https://www.gstatic.com/firebasejs/7.12.0/firebase-app.js');
  importScripts('https://www.gstatic.com/firebasejs/7.12.0/firebase-messaging.js');
  
  firebase.initializeApp({ ... });
  
  const messaging = firebase.messaging();
  
  self.addEventListener('activate', event =&gt; {
      console.log('Service worker activating...');
  
      // Add the public key generated from the console here.
      messaging.usePublicVapidKey();
  
      // Get Instance ID token. Initially this makes a network call, once retrieved
      // subsequent calls to getToken will return from cache.
      messaging.getToken().then((currentToken) =&gt; {
          console.log("currentToken", currentToken);
  
          if (currentToken) {
              // sendTokenToServer(currentToken);
          } else {
              console.error('No Instance ID token available. Request permission to generate one.');
          }
      }).catch((err) =&gt; {
          console.error('An error occurred while retrieving token. ', err);
      });
  
      messaging.setBackgroundMessageHandler(function(payload) {
          console.log('[firebase-messaging-sw.js] Received background message ', payload);
      });
  });
  </code></pre>
  
  <p>If this service worker is started like so:</p>
  
  <pre><code>if ('serviceWorker' in navigator) {
      window.addEventListener('load', () =&gt; {
          navigator.serviceWorker.register('js/service-worker.js')
          .then(registration =&gt; {
              console.log('Service Worker is registered', registration);
          })
          .catch(err =&gt; {
              console.error('Registration failed:', err);
          });
      });
  }
  </code></pre>
  
  <p>Is it a problem if the <code>onTokenRefresh</code> callback is never handled, given that this can only be handled in the foreground.</p>
  
  <p>Does this setup of FCM seem correct?</p>