GoogleChromeLabs / web-push-codelab

Other
556 stars 291 forks source link

Push notification isn't working when I launched a push from application tab in chrome. #49

Closed vaibhavarora14 closed 3 years ago

vaibhavarora14 commented 7 years ago

Code:

/*
*
*  Push Notifications codelab
*  Copyright 2015 Google Inc. All rights reserved.
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      https://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License
*
*/

/* eslint-env browser, es6 */

'use strict';

const applicationServerPublicKey = 'BD_yzu1gOR7RvV-Zg_jHpOnin12d5qR6DH5SrqdCDBYlB2Ly7rvwpw1pjj_RUVpOp_uU4FK4E8i6J_0yggqr3js';

const pushButton = document.querySelector('.js-push-btn');

let isSubscribed = false;
let swRegistration = null;

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;
}

if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

  navigator.serviceWorker.register('sw.js')
  .then(function(swReg) {
    console.log('Service Worker is registered', swReg);

    swRegistration = swReg;
    initialiseUI();
  })
  .catch(function(error) {
    console.error('Service Worker Error', error);
  });
} else {
  console.warn('Push messaging is not supported');
  pushButton.textContent = 'Push Not Supported';
}

function initialiseUI() {
  pushButton.addEventListener('click', function() {
    pushButton.disabled = true;
    if (isSubscribed) {
      // TODO: Unsubscribe user
    } else {
      subscribeUser();
    }
  });

  // Set the initial subscription value
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    isSubscribed = !(subscription === null);

    updateSubscriptionOnServer(subscription);

    if (isSubscribed) {
      console.log('User IS subscribed.');
    } else {
      console.log('User is NOT subscribed.');
    }

    updateBtn();
  });
}

function subscribeUser() {
  const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);

  swRegistration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: applicationServerKey
  })
  .then(function(subscription) {
    console.log('User is subscribed.');

    updateSubscriptionOnServer(subscription);

    isSubscribed = true;

    updateBtn();
  })
  .catch(function(err) {
    console.log('Failed to subscribe the user: ', err);
    updateBtn();
  });
}

function updateBtn() {
    if(Notification.permission == 'denied') {
        pushButton.textContent = 'Push Messaging Blocked.';
        pushButton.disabled = true;
        updateSubscriptionOnServer(null);
        return;
    }

    if(isSubscribed) {
        pushButton.textContent = 'Disable Push Messaging';
    } else {
        pushButton.textContent = 'Enable Push Messaging';
    }

    pushButton.disabled = false;
}

function updateSubscriptionOnServer(subscription) {
  // TODO: Send subscription to application server

  const subscriptionJson = document.querySelector('.js-subscription-json');
  const subscriptionDetails =
    document.querySelector('.js-subscription-details');

  if (subscription) {
    subscriptionJson.textContent = JSON.stringify(subscription);
    subscriptionDetails.classList.remove('is-invisible');
  } else {
    subscriptionDetails.classList.add('is-invisible');
  }
}

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

  const title = 'Push Codelab';
  const options = {
    body: 'Yay it works.',
    icon: 'images/icon.png',
    badge: 'images/badge.png'
  };

  event.waitUntil(self.registration.showNotification(title, options));
});
gauntface commented 7 years ago

@varora1406 could you please explain a little more about what you mean by "when I launched a push from application tab in chrome"

colepacak commented 7 years ago

@varora1406, the push event listener needs to go in sw.js, not main.js. It got me too.

It makes sense because self refers to the service worker itself.

gauntface commented 7 years ago

Ah got you. @colepacak @varora1406 could you suggest any ways to improve the code to make this more obvious?

colepacak commented 7 years ago

@gauntface, after looking back at the docs, you're pretty clear on the fact that the service worker code belongs in sw.js, but I blew right past it as I was going through the tutorial.

One thing that may help is to add one of those slick blue callouts with the blue star (with the "note" CSS class) right after the initial service worker code reminding users that sw.js is the home for all of the service worker event listeners.

Thanks for the great docs.

DanJ210 commented 6 years ago

Everything was working fine up until adding the event listener to sw.js. I've added the code but the push button in dev tools does not send a push. The event isn't triggered at all whatsoever. Doesn't matter if I unregister and restart the site. Why wouldn't the event listener be working?

Abraham21 commented 6 years ago

@DanJ210 did you solve this? I have the same problem right now.

DanJ210 commented 6 years ago

@Abraham21 On my personal computer I was able to send a push from a push service but not the "Push" button in dev tools. So the event listener seems to be working but the "Push" button in dev tools seems to not be working.

RedSpeeds commented 6 years ago

@DanJ210 Did you find a fix at my end the push button in the chrome devtools also seems to be not functioning when i try to send a push message using a site it works but not when i try it using chrome devtools

DanJ210 commented 6 years ago

@TheCreeperCow Nope, unfortunately not. It seems like the push button in dev tools doesn't work for anyone here. Or if it does then it's not working for this type of project. Though the code is an event listener so it seems as if dev tools isn't emiting the proper event or an event at all. Idk I'm just guessing.

noobling commented 6 years ago

If you look at the pictures from the docs https://developers.google.com/web/ilt/pwa/tools-for-pwa-developers#update they are different to what the latest chrome interface is maybe this worked on older chrome?

DanJ210 commented 6 years ago

@noobling it's very possible. We are using Google's own training so you'd think there'd be some heads up to Google people if a major tool is changing. Have you worked through this course?

myakura commented 6 years ago

I just run into the same issue. It looks like a bug in DevTools.

849241 - Service worker's Push/Sync locally triggered events don't work - chromium - Monorail https://bugs.chromium.org/p/chromium/issues/detail?id=849241

akonyer commented 6 years ago

Getting the exact same behavior. I can not use the Push button to test my service worker.

All other events fire no problem (Install, Activate) but push doesn't even fire at all using the "Push" test button.

TheSecurityBunker commented 6 years ago

Wasted about 3 hours to find out Chrome is broke. Download Chrome Dev. Latest version has the button fixed. Can run it along side your normal Chrome, so no need to uninstall anything...

Danhiler commented 5 years ago

Had the same issue, used chrome canary to fix this

kimdugong commented 5 years ago

Check your chrome version now. Version 71.0.3578.80would be work correctly. Previous version(70.0.3538.110?) of chrome didn't work in my case.

Acanguven commented 5 years ago

Works great on version 71.0.3578.80

annaelizabeth2019 commented 4 years ago

Similar issue, here. Sometimes notifications do not show on some systems. My Chrome is 78.0.3904.70 so is my product manager's, but he cannot get the notifications to show up. I can see the service-worker receive the payload and everything.

vergilius commented 3 years ago

For anyone else struggling with the issue: make sure your push listener is in the service worker itself.

kha1989led commented 2 years ago

If you are sure your service worker is registered in the browser but your 'push' event is not getting triggered, you can debug all incoming push notifications to Google Chrome by doing the following:

  1. Open chrome://gcm-internals
  2. Start recording
  3. Send a test push notification to the browser
  4. Observe the logs

The server was getting a 201 on the push request and the browser threw no errors in the console log. However, I was having a decryption issue. The browser was receiving the push notification but failed to decrypt it: AES-GCM decryption failed.

Helpful Source: https://developers.google.com/web/fundamentals/push-notifications/common-issues-and-reporting-bugs