push event not triggered in service worker












1















Following this tutorial until "Handle push event" section to setup a desktop notification system in my application, I face a problem:



When I click "push" to push a notification artificially with Chrome, no notification appear. No message in the console.



I allowed the notification from the website and the service-worker is well installed in my browser.



My service worker looks like this:



self.addEventListener('push', function (event) {
console.log('[Service Worker] Push Received.')
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`)

const title = 'My App Name'
const options = {
body: event.data.text(),
icon: 'pwa/icon.png',
badge: 'pwa/badge.png'
}

const notificationPromise = self.registration.showNotification(title, options)
event.waitUntil(notificationPromise)
})




and my service worker registration (using register-service-worker npm package) looks like this:



import { register } from 'register-service-worker'

const applicationServerPublicKey = 'BI5qCj0NdNvjDcBYTIXiNccdcP74Egtb3WxuaXrHIVCLdM-MwqPkLplHozlMsM3ioINQ6S_HAexCM0UqKMvaYmg'

function urlB64ToUint8Array (base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4)
const base64 = (base64String + padding)
.replace(/-/g, '+')
.replace(/_/g, '/')

const rawData = window.atob(base64)
const outputArray = new Uint8Array(rawData.length)

for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i)
}
return outputArray
}

async function manageNotificationSubscription (registration) {
const subscription = await registration.pushManager.getSubscription()
let isSubscribed: boolean = !(subscription === null)

if (isSubscribed) {
console.log('User IS subscribed.')
} else {
console.log('User is NOT subscribed.')
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey)
try {
await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
console.log('User just subscribed.')
} catch (e) {
console.error('Failed to subscribe the user: ', e)
}
}
}

if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready () {
console.log(
'App is being served from cache by a service worker.'
)
},
async registered (registration) {
console.log('Service worker has been registered.')
await manageNotificationSubscription(registration)
},
cached () {
console.log('Content has been cached for offline use.')
},
updated () {
console.log('New content is available; please refresh.')
},
offline () {
console.log('No internet connection found. App is running in offline mode.')
},
error (error) {
console.error('Error during service worker registration:', error)
}
})
}




It looks like the push event in the service-worker is not even triggered...
Did I do something wrong?










share|improve this question



























    1















    Following this tutorial until "Handle push event" section to setup a desktop notification system in my application, I face a problem:



    When I click "push" to push a notification artificially with Chrome, no notification appear. No message in the console.



    I allowed the notification from the website and the service-worker is well installed in my browser.



    My service worker looks like this:



    self.addEventListener('push', function (event) {
    console.log('[Service Worker] Push Received.')
    console.log(`[Service Worker] Push had this data: "${event.data.text()}"`)

    const title = 'My App Name'
    const options = {
    body: event.data.text(),
    icon: 'pwa/icon.png',
    badge: 'pwa/badge.png'
    }

    const notificationPromise = self.registration.showNotification(title, options)
    event.waitUntil(notificationPromise)
    })




    and my service worker registration (using register-service-worker npm package) looks like this:



    import { register } from 'register-service-worker'

    const applicationServerPublicKey = 'BI5qCj0NdNvjDcBYTIXiNccdcP74Egtb3WxuaXrHIVCLdM-MwqPkLplHozlMsM3ioINQ6S_HAexCM0UqKMvaYmg'

    function urlB64ToUint8Array (base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4)
    const base64 = (base64String + padding)
    .replace(/-/g, '+')
    .replace(/_/g, '/')

    const rawData = window.atob(base64)
    const outputArray = new Uint8Array(rawData.length)

    for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i)
    }
    return outputArray
    }

    async function manageNotificationSubscription (registration) {
    const subscription = await registration.pushManager.getSubscription()
    let isSubscribed: boolean = !(subscription === null)

    if (isSubscribed) {
    console.log('User IS subscribed.')
    } else {
    console.log('User is NOT subscribed.')
    const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey)
    try {
    await registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: applicationServerKey
    })
    console.log('User just subscribed.')
    } catch (e) {
    console.error('Failed to subscribe the user: ', e)
    }
    }
    }

    if (process.env.NODE_ENV === 'production') {
    register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
    console.log(
    'App is being served from cache by a service worker.'
    )
    },
    async registered (registration) {
    console.log('Service worker has been registered.')
    await manageNotificationSubscription(registration)
    },
    cached () {
    console.log('Content has been cached for offline use.')
    },
    updated () {
    console.log('New content is available; please refresh.')
    },
    offline () {
    console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
    console.error('Error during service worker registration:', error)
    }
    })
    }




    It looks like the push event in the service-worker is not even triggered...
    Did I do something wrong?










    share|improve this question

























      1












      1








      1








      Following this tutorial until "Handle push event" section to setup a desktop notification system in my application, I face a problem:



      When I click "push" to push a notification artificially with Chrome, no notification appear. No message in the console.



      I allowed the notification from the website and the service-worker is well installed in my browser.



      My service worker looks like this:



      self.addEventListener('push', function (event) {
      console.log('[Service Worker] Push Received.')
      console.log(`[Service Worker] Push had this data: "${event.data.text()}"`)

      const title = 'My App Name'
      const options = {
      body: event.data.text(),
      icon: 'pwa/icon.png',
      badge: 'pwa/badge.png'
      }

      const notificationPromise = self.registration.showNotification(title, options)
      event.waitUntil(notificationPromise)
      })




      and my service worker registration (using register-service-worker npm package) looks like this:



      import { register } from 'register-service-worker'

      const applicationServerPublicKey = 'BI5qCj0NdNvjDcBYTIXiNccdcP74Egtb3WxuaXrHIVCLdM-MwqPkLplHozlMsM3ioINQ6S_HAexCM0UqKMvaYmg'

      function urlB64ToUint8Array (base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4)
      const base64 = (base64String + padding)
      .replace(/-/g, '+')
      .replace(/_/g, '/')

      const rawData = window.atob(base64)
      const outputArray = new Uint8Array(rawData.length)

      for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i)
      }
      return outputArray
      }

      async function manageNotificationSubscription (registration) {
      const subscription = await registration.pushManager.getSubscription()
      let isSubscribed: boolean = !(subscription === null)

      if (isSubscribed) {
      console.log('User IS subscribed.')
      } else {
      console.log('User is NOT subscribed.')
      const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey)
      try {
      await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: applicationServerKey
      })
      console.log('User just subscribed.')
      } catch (e) {
      console.error('Failed to subscribe the user: ', e)
      }
      }
      }

      if (process.env.NODE_ENV === 'production') {
      register(`${process.env.BASE_URL}service-worker.js`, {
      ready () {
      console.log(
      'App is being served from cache by a service worker.'
      )
      },
      async registered (registration) {
      console.log('Service worker has been registered.')
      await manageNotificationSubscription(registration)
      },
      cached () {
      console.log('Content has been cached for offline use.')
      },
      updated () {
      console.log('New content is available; please refresh.')
      },
      offline () {
      console.log('No internet connection found. App is running in offline mode.')
      },
      error (error) {
      console.error('Error during service worker registration:', error)
      }
      })
      }




      It looks like the push event in the service-worker is not even triggered...
      Did I do something wrong?










      share|improve this question














      Following this tutorial until "Handle push event" section to setup a desktop notification system in my application, I face a problem:



      When I click "push" to push a notification artificially with Chrome, no notification appear. No message in the console.



      I allowed the notification from the website and the service-worker is well installed in my browser.



      My service worker looks like this:



      self.addEventListener('push', function (event) {
      console.log('[Service Worker] Push Received.')
      console.log(`[Service Worker] Push had this data: "${event.data.text()}"`)

      const title = 'My App Name'
      const options = {
      body: event.data.text(),
      icon: 'pwa/icon.png',
      badge: 'pwa/badge.png'
      }

      const notificationPromise = self.registration.showNotification(title, options)
      event.waitUntil(notificationPromise)
      })




      and my service worker registration (using register-service-worker npm package) looks like this:



      import { register } from 'register-service-worker'

      const applicationServerPublicKey = 'BI5qCj0NdNvjDcBYTIXiNccdcP74Egtb3WxuaXrHIVCLdM-MwqPkLplHozlMsM3ioINQ6S_HAexCM0UqKMvaYmg'

      function urlB64ToUint8Array (base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4)
      const base64 = (base64String + padding)
      .replace(/-/g, '+')
      .replace(/_/g, '/')

      const rawData = window.atob(base64)
      const outputArray = new Uint8Array(rawData.length)

      for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i)
      }
      return outputArray
      }

      async function manageNotificationSubscription (registration) {
      const subscription = await registration.pushManager.getSubscription()
      let isSubscribed: boolean = !(subscription === null)

      if (isSubscribed) {
      console.log('User IS subscribed.')
      } else {
      console.log('User is NOT subscribed.')
      const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey)
      try {
      await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: applicationServerKey
      })
      console.log('User just subscribed.')
      } catch (e) {
      console.error('Failed to subscribe the user: ', e)
      }
      }
      }

      if (process.env.NODE_ENV === 'production') {
      register(`${process.env.BASE_URL}service-worker.js`, {
      ready () {
      console.log(
      'App is being served from cache by a service worker.'
      )
      },
      async registered (registration) {
      console.log('Service worker has been registered.')
      await manageNotificationSubscription(registration)
      },
      cached () {
      console.log('Content has been cached for offline use.')
      },
      updated () {
      console.log('New content is available; please refresh.')
      },
      offline () {
      console.log('No internet connection found. App is running in offline mode.')
      },
      error (error) {
      console.error('Error during service worker registration:', error)
      }
      })
      }




      It looks like the push event in the service-worker is not even triggered...
      Did I do something wrong?







      push-notification service-worker






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 10:14









      Victor CastroVictor Castro

      591324




      591324
























          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335684%2fpush-event-not-triggered-in-service-worker%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53335684%2fpush-event-not-triggered-in-service-worker%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Danny Elfman

          Lugert, Oklahoma