Code Monkey home page Code Monkey logo

web-push-codelab's Introduction

Push Notifications codelab

Code for the Web Fundamentals Push Notifications codelab.

In this codelab, you'll learn how to add Push Notifications to web applications. This will enable you to re-engage users with breaking news and information about new content.

You'll also learn the basics of Service Workers.

What you'll learn

  • Service Worker basics: installation and event handling
  • How to set up a Google Cloud Messaging (GCM) account
  • How to add a web manifest
  • Techniques for requesting GCM to send a notification to a web client
  • Notification display
  • Notification click handling

Example code for each step of the codelab is available from the completed directory.

License

Copyright 2015 Google, Inc.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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

http://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.

web-push-codelab's People

Contributors

gauntface avatar samdutton avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web-push-codelab's Issues

End point

Where do I find the endpoint? I can't seem to find it.

Truncated text

image

When attempting to test the push notifications tutorial with the push companion, the page complains that the subscription endpoint is truncated when it is not.

There are no further error messages.

Version 56.0.2924.87 (64-bit) OS X 10.10.5

Notification failed on Chrome Android

We have juste implemented chrome push notifications following your sample and it works fine for users on chrome desktop but failed for chrome android users. We get the response bellow
result [{"failure":1,"results":[{"error":"MismatchSenderId"}],"success":0,"multicast_id":5148666477777647844,"canonical_ids":0}]

function call in the services worker

I need some function to be executed every time when push notification is called(view in browser), so how to execute function call in the services worker. Thankyou

UnauthorizedRegistration error

I'm doing this tutorial using the code samples, and having folder "08-completed" running in my Chrome WebServer.
But when I try to use the companion app at https://web-push-codelab.appspot.com/ or use web-push module on my local machine I get a "UnauthorizedException" error.

$ web-push send-notification --endpoint=https://fcm.googleapis.com/fcm/send/XXXX
Error sending push message:
{ [WebPushError: Received unexpected response code]
  name: 'WebPushError',
  message: 'Received unexpected response code',
  statusCode: 400,
  headers:
   { 'content-type': 'text/html; charset=UTF-8',
     date: 'Fri, 25 Nov 2016 08:54:08 GMT',
     expires: 'Fri, 25 Nov 2016 08:54:08 GMT',
     'cache-control': 'private, max-age=0',
     'x-content-type-options': 'nosniff',
     'x-frame-options': 'SAMEORIGIN',
     'x-xss-protection': '1; mode=block',
     server: 'GSE',
     'alt-svc': 'quic=":443"; ma=2592000; v="36,35,34"',
     'accept-ranges': 'none',
     vary: 'Accept-Encoding',
     connection: 'close' },
  body: '<HTML>\n<HEAD>\n<TITLE>UnauthorizedRegistration</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>UnauthorizedRegistration</H1>\n<H2>Error 400</H2>\n</BODY>\n</HTML>\n' }

Same error I get form the companion app.

Any idea what am I missing / doing wrong?

multiple site

Hello i want to put script in a lot of my website, but in all the web site in to register to the serviceWorker
, when i try to do it from the script is says me that there is problem because the origin url . what can i do to fix it , but i dont want to upload every site the file

Chrome push test does not display push notification

I've followed the tutorial up to the "Handle a push event section".
At the end of this section, I click the chrome devtools "Push" button, but no push notification is displayed on screen.
The service worker "sw.js" is executed as I can see the console log output and it reads:

[Service Worker] Push Received.
[Service Worker] Push had this data: "Test push message from DevTools."

But no push notification.
I'm using a 2013 macbook air running 10.12.3 & Chrome version 57

Is this just something I've done wrong or is this a common problem?

CURL command not working in Step 7

Following the instructions on https://developers.google.com/web/fundamentals/getting-started/push-notifications/step-07?hl=en when I executed the referenced CURL command I was getting just a "to" response in the command line.

I finally got it working by modifying the CURL to curl --header "Authorization: key=XXXXXX" --header "Content-Type: application/json" https://gcm-http.googleapis.com/gcm/send -d "{\"to\":\"XXXXXX\"}"

Is this correct, or was I doing something wrong?

"This video is private"

In step "11. Handle notification clicks", the provided code snippet contains a reference to https://youtu.be/gYMkEMCHtJ4.

Expected outcome: Clicking on the push notification leads to a nice video.
Actual outcome: Clicking on the push notification leads to a "This video is private" error message.

Codelab must be updated to the new version of GCM console

Hi y'all... We were trying to use this codelab https://codelabs.developers.google.com/codelabs/push-notifications/index.html at Progressive Web Apps Roadshow Sub-Saharan Africa but the GCM console log has changed a lot and the instructions are wrong.
Step 8 using curl always returns this error:
{"multicast_id":8288173565418041385,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

Better yet it would be amazing see updated to use FCM 🔥

Option to record received notifications on browser

Most of the web Apps are pushing multiple notification in small intervals; if one opens browser after a some period, We get multiple notification and it's very difficult and time consuming to go through each one of them. There should be an option to record notification in a bookmark on receive event so that they can be read later.

Typos in Step 8

  1. First sentence => Missing the word "of" in this sentence:

If you click on one of these notifications you'll notice nothing happens.

  1. Try it out Section => Delete unneeded word "this"

Try triggering a push message in DevTools again and this click on the notification.

Correction:

Try triggering a push message in DevTools again and click on the notification.

Link to WebPush Protocol points to expired document

Hey 👋

Going through the: Web Fundamentals - Getting Started - Your first push notifications web app, codelab/tutorial/guide thing and noticed that on step 4 "Make a project on the Google Developers Console" the link to the Web Push Protocol points to:

https://datatracker.ietf.org/doc/draft-thomson-webpush-protocol/

This appears to be of status expired and archived and could cause confusion, I believe:

https://datatracker.ietf.org/doc/draft-ietf-webpush-protocol/

is the current actively worked version.

Apologies for opening the issue here in case it's not the right location to report this, couldn't find the docs themselves here in Github.

Thanks,
.FxN

ps. great work on the guide so far, not looked at any of these before and so far it's been really easy to follow and clear 👍

notificationclick don't check for opened tabs

The notificationclick method is said to check for opened tabs and only open a new tab if the URL isn't already open. It isn't working like this. Even if I have the tab opened, clicking the push open a new tab on the same URL again.

From the tutorial:

"This code checks all window clients for this Service Worker; if the requested URL is already open in a tab, focus on it — otherwise open a new tab for it."

6. Handle Permission Denied

In the titled part of the codelab, should not the following code line towards the end of the function updateBtn should be removed as it otherwise turns the button ON back?

pushButton.disabled = false;

Documentation.

app/ should contain the completed app (not just TODO stubs).

Invalid registration error while executing the curl cmd

I have couple of questions

  1. is it necessary to create sample Project name in Firebase or just sender_id match would help?

  2. After opening my project in chrome web server, I used the curl cmd to send the notification
    curl --header "Authorization: key=AIzaSyBjxxxxxx" --header "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{"registration_ids":["xxxx"]}"

This throws error
{"multicast_id":7720103039622715939,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

I have tried all the possibilites. How to resolve this

Is there any other way to write code for sending push notifications other than curl ?

Web Push Libraries

Hi! When I completed the codelab, went straight to the Web Push Libraries to implement the "server side part" of the whole story. Tried to integrate the pywebpush library to my project but I found out it wasn't as straightforward as it should be (at least for me) and finally ended up coding solidwebpush, a library that works right "out of the box" for someone who has completed the codelab. It may be useful for someone else working with python too... idk...

Google Cloud Messaging (GCM) or Firebase?

This repository explains Push Notification with Google Cloud Messaging (GCM) account but at this time, when trying to access the Google Cloud Messaging (GCM) account, the page refer to use Firebase. In fact, I couldn't find a way to get a API key that work with Google Cloud Messaging (GCM). My understanding is that it is deprecated. Is the documentation will be updated or we should just rely on the Firebase documentation from this point?

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

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

Subscription alert not coming in app server

In the application server, when i run the given code, it wont ask for user subscription and is giving an error "Failed to subscribe the user: DOMException: Subscription failed - no active Service Worker". But it works fine on google chrome server. Pls help. i am using Tomcat server

Not getting Push message from Push Companion Site

I have followed codelab steps and created successfully push notification sample and able to get notification from Devtool when I click push. But when I copy paste the subscription and pushed message from Push Companion Site, I didn't get push notification on my browser.

MismatchSenderId Problem

Hello,
I have followed your tutorial step by step. However I get MismatchSenderId. Please, lead me to solve this problem.

Missing function from tutorial

Tutorial does not have urlB64ToUint8Array function declared.

When user will try to make Push Notifications work, they will end up with non existing urlB64ToUint8Array method.

Please include sample into tutorial

Incorrect Preview of screenshots

Incorrect Preview of screenshots

Issue:

The following screenshot indicates the developer to navigate to localhost:8887. The developer is not able to run the application with this URL:

screen shot 2016-11-29 at 10 54 15 am

Solution:

The developer needs to navigate to localhost:8887/app/ to run the application and see the changes made in the code.

screen shot 2016-11-29 at 11 29 50 am

Failed to subscribe the user

i am getting the error, "Failed to subscribe the user: DOMException: Subscription failed - no active Service Worker" in my Https tomcat server when i press the enable button..PLS help

How to send payload

Im sending the some JSON data as payload to GCM, but how to receive here the payload on event PUSH.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.