Search code examples
javascriptpush-notificationprogressive-web-appsservice-workerweb-push

navigator.serviceWorker.ready promise not getting resolved on push notifications on Production... Actually the code is working on development


I want to run the function configurePushSub down bellow whenever an event is fired on a page for my create-react-app... It is working everything fine on development mode, however when I hosted my app on Netlify the promise navigator.serviceWorker.ready is not getting resolved as I cannot see the message in the console navigator has loaded... I have already tried everything possible to get that working but everything unsuccessfull

  function configurePushSub() {
    if (!('serviceWorker' in navigator)) {
      return;
    }
    let hasUnsubscribed;
    var reg;
    console.log(
      'running',
      navigator.serviceWorker,
      navigator.serviceWorker.ready
    );
    navigator.serviceWorker.ready
      .then(function (swreg) {
        console.log(swreg, 'navigator has loaded');
        reg = swreg;
        return swreg.pushManager.getSubscription();
      })
      .then((sub) => {
        if (!!sub) {
          return sub.unsubscribe().then(function (s) {
             hasUnsubscribed = true;
            return navigator.serviceWorker.ready;
          });
        }
        return navigator.serviceWorker.ready;
      })
      .then(function (sub) {
        var vapidPublicKey =
          'BOChVD1tKTc0Of3c-0JplT1y5FPOm6oijP_4stWBXwoQe6xI4GGt6cnpdu4JLwt_Znj23bj_hku8OSois1y9fLE';

        var convertedVapidPublicKey = urlBase64ToUint8Array(vapidPublicKey);

        return reg.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: convertedVapidPublicKey,
        });
      })
      .then(async function (newSub) {
        let key;
        let authSecret;
        let endPoint;
        if (newSub) {
          const rawKey = newSub.getKey ? newSub.getKey('p256dh') : '';
          key = rawKey
            ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey)))
            : '';
          var rawAuthSecret = newSub.getKey ? newSub.getKey('auth') : '';
          authSecret = rawAuthSecret
            ? btoa(
                String.fromCharCode.apply(null, new Uint8Array(rawAuthSecret))
              )
            : '';

          endPoint = newSub.endpoint;
          const config = {
            headers: {
              'Content-Type': 'application/json',
              Authorization: `Bearer ${token}`,
            },
          };
          const gpuTier = await getGPUTier();
          const info = getOperatingSystemName(this);
          console.log(info);
          if (hasUnsubscribed) {
            await axios.put(
              `${Config.SERVER_ADDRESS}/api/pushNotifications/id`,
              {
                endpoint: endPoint,
                key,
                auth: authSecret,
                gpu: gpuTier.gpu,
                operating_system: `${info.os} ${info.osVersion}`,
                device: info.mobile ? 'mobile' : 'desktop',
                browser: `${info.browser} ${info.browserMajorVersion}`,
                operating_system_architecture: info.arch,
              },
              config
            );
          } else {
            await axios.post(
              `${Config.SERVER_ADDRESS}/api/pushNotifications/`,
              {
                endpoint: endPoint,
                key,
                auth: authSecret,
                gpu: gpuTier.gpu,
                operating_system: `${info.os} ${info.osVersion}`,
                device: info.mobile ? 'mobile' : 'desktop',
                browser: `${info.browser} ${info.browserMajorVersion}`,
                operating_system_architecture: info.arch,
              },
              config
            );
          }
        }
      })
      .then(function (res) {
        displayConfirmNotification();
      })
      .catch(function (err) {
        console.log(err);
      });
  }

Solution

  • I have just managed to get that working... It is just that I haven't registered the service worker for the production mode... When I was on development I have written the following code, but then I moved to the production and I have forgotten about it.

    navigator.serviceWorker.register(`/sw.js`)