SlideShare une entreprise Scribd logo
1  sur  6
Télécharger pour lire hors ligne
Implement GCM Push Notification for Websites
ninjacoders.info/2016/07/gcm-push-notification-for-website.html
If you ask a developer what feature is missing in web application, the first answer is PUSH
NOTIFICATION. Notification is a great way to engage users to your website. So today i'm
explaining push notification using Google Cloud Messaging for websites.
Project structure:
+-gcm-push-demo
|+-----images
|+--------icon192x192.png
|+-----index.html
|+-----manifest.json
|+-----myworker.js
Download Script Live Demo
Following are the steps we have to follow for implementing push messaging for
chrome browser.
1. Check if browser supports service worker & push messaging.
2. Request user for push notification permission.
3. Register a service worker with your browser.
4. Get Server API key and Sender ID from GCM.
5. Create manifest file.
6. Subscribe for push messaging.
7. Write some code for myworker.js
1/6
8. Integrate all peace of code.
9. Send push message to Website.
Check if browser supports service worker and push messaging.
//check if serviceWorker prsent in navigator
if(‘serviceWorker’ in navigator) {
console.log('service worker is supported');
} else {
console.warn('user denied the permission');
}
//check if push messaging supported or not
if('pushManager' in window) {
console.log('push messaging is supported');
}
else {
console.log('push messaging is not supported');
}
Request user for push notification permission.
Notification.requestPermission().then(function(permission) {
if(permission === 'granted') {
//here you can register your service worker
} else {
console.log('service worker not present');
}
});
Register a service worker with your browser.
Before registering a service worker with browser we will need service worker file
which needs to be registered with service worker. Create a blank myworker.js file
for now.
navigator.serviceWorker.register(‘/myworker.js’).then(function(registration){
console.log(‘service worker registered with scope: ‘, registration.scope);
}).catch(function(err){
console.error(‘service worker registration failed: ‘, err);
});
Get Server API key and Sender ID from GCM.
Generating server key and sender id is simple go to GCM websites and follow the
instructions or you can follow my video tutorial.
Create a web manifest file.
The web app manifest provides information about an application in a simple document.
We have to add gcm_sender_id in manifest file for subscribing to GCM server.
manifest.json
2/6
{
"name": "Web Push Demo",
"short_name": "GCM Push",
"icons": [{
"src": "images/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
}],
"start_url": "/index.html",
"display": "standalone",
"gcm_sender_id": "sender-id"
}
Subscribe to GCM for push messaging.
Finally we have to subscribe to GCM server using subscribe() method on the
PushManager object through the serviceWorkerRegistration object.
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration){
serviceWorkerRegistration.pushManger.subscribe({userVisibleOnly:true})
.then(function(subscription){
console.log(‘subscription successful: ‘, subscription);
}).catch(function(err){
console.error(‘unable to subscribe to GCM’, err);
});
});
Write some code for myworker.js
myworker.js is the file which will be running in service worker thread of your web
browser. Service worker is a javascript which is run by your browser in the
background, write some code for receiving push message into your website.
myworker.js
self.addEventListener('push', function(event) {
console.log('Push message received');
var notificationTitle = 'New Message';
const notificationOptions = {
body: 'Push mesage received',
icon: './images/icon-192x192.png',
tag: 'simple-push-demo-notification',
data: {
url: 'http://ninjacoders.info'
}
};
event.waitUntil(
Promise.all([
self.registration.showNotification(
notificationTitle, notificationOptions)
])
);
});
Above code will register an event listener for push messages and whenever push
message comes from GCM this event get triggered.
3/6
self.addEventListener('notificationclick', function(event) {
event.notification.close();
var clickResponsePromise = Promise.resolve();
if (event.notification.data && event.notification.data.url) {
clickResponsePromise = clients.openWindow(event.notification.data.url);
}
event.waitUntil(
Promise.all([
clickResponsePromise
])
);
});
Above code will register an event listener for notificationClick event and whenever
user clicks on the notification window we will open a new web page.
Integrate all peace of code.
index.html
4/6
<!DOCTYPE html>
<html>
<head>
<title>Push Notification for Web Application</title>
<link rel="manifest" href="/manifest.json">
<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelector("#enablepush")
.addEventListener('click', function(e) {
if(Notification.permission !== 'granted') {
Notification.requestPermission().then(function(permission) {
if(permission === 'granted' && 'serviceWorker' in navigator) {
navigator.serviceWorker.register('myworker.js')
.then(initialiseState);
} else {
console.log('service worker not present');
}
});
}
});
//get subscription token if already subscribed
if(Notification.permission === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
registration.pushManager.getSubscription()
.then(function(subscription){
getToken(subscription);
});
});
}
});
function initialiseState() {
//check if notification is supported or not
if(!('showNotification' in ServiceWorkerRegistration.prototype)) {
console.warn('Notificaiton are not supported');
return;
}
//check if user has blocked push notification
if(Notification.permission === 'denied'){
console.warn('User has blocked the notification');
}
//check if push messaging is supported or not
if(!('PushManager' in window)) {
console.warn('Push messaging is not supported');
return;
}
//subscribe to GCM
navigator.serviceWorker.ready
.then(function(serviceWorkerRegistration) {
//call subscribe method on serviceWorkerRegistration object
serviceWorkerRegistration.pushManager
.subscribe({userVisibleOnly: true})
.then(function(subscription){
getToken(subscription);
}).catch(function(err){
console.error('Error occured while subscribe(): ', err);
});
});
}
function getToken(subscription) {
console.log(subscription);
var token = subscription.endpoint
.substring(40, subscription.endpoint.length);
document.querySelector("#token").innerHTML = token;
}
</script>
</head>
<body>
<h1>Push Notification for Web Application</h1>
<button id="enablepush">Enable Push</button><br />
<label for="token">Registration ID</label>
<textarea id="token" rows="6" cols="40"></textarea>
</body>
</html>
Send push message to Website.
5/6
Sending push notification we use GCM, we have to send post request to GCM along with
authorization key (Server Key) and client token (i.e registration id)
https://gcm-http.googleapis.com/gcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...fMwj0qwRt-bJvir
{
"data":
{
"message": "How to create PayPal",
"url": "http://www.ninjacoders.info/"
},
"to" : "fzeh02y7_p4:APA91bE-KxSmlLoJFyZftBlUkNsVXW..."
}
curl "https://android.googleapis.com/gcm/send" --request POST --header "Authorization: key=server_key" --header
"Content-Type: application/json" -d "{"to":"client_token"}"
For sending push messages to your website you have to make POST request from your
server copy paste above 'curl' and place your server_key and client_token. You can
also use this tool and enter your server_key and client_token click on send
notification button.
Note: HTTPS is needed to register service worker on production but you can test it
without HTTPS on your local server url should be http://localhost
You can use node http-server for deploy the app or you can use any server like
wampp, xampp, lampp.
Final Words:
Integrate push notification in your website and engage more users.
6/6

Contenu connexe

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

En vedette

Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Saba Software
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming Language
Simplilearn
 

En vedette (20)

How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming Language
 

Implement gcm push notification for websites

  • 1. Implement GCM Push Notification for Websites ninjacoders.info/2016/07/gcm-push-notification-for-website.html If you ask a developer what feature is missing in web application, the first answer is PUSH NOTIFICATION. Notification is a great way to engage users to your website. So today i'm explaining push notification using Google Cloud Messaging for websites. Project structure: +-gcm-push-demo |+-----images |+--------icon192x192.png |+-----index.html |+-----manifest.json |+-----myworker.js Download Script Live Demo Following are the steps we have to follow for implementing push messaging for chrome browser. 1. Check if browser supports service worker & push messaging. 2. Request user for push notification permission. 3. Register a service worker with your browser. 4. Get Server API key and Sender ID from GCM. 5. Create manifest file. 6. Subscribe for push messaging. 7. Write some code for myworker.js 1/6
  • 2. 8. Integrate all peace of code. 9. Send push message to Website. Check if browser supports service worker and push messaging. //check if serviceWorker prsent in navigator if(‘serviceWorker’ in navigator) { console.log('service worker is supported'); } else { console.warn('user denied the permission'); } //check if push messaging supported or not if('pushManager' in window) { console.log('push messaging is supported'); } else { console.log('push messaging is not supported'); } Request user for push notification permission. Notification.requestPermission().then(function(permission) { if(permission === 'granted') { //here you can register your service worker } else { console.log('service worker not present'); } }); Register a service worker with your browser. Before registering a service worker with browser we will need service worker file which needs to be registered with service worker. Create a blank myworker.js file for now. navigator.serviceWorker.register(‘/myworker.js’).then(function(registration){ console.log(‘service worker registered with scope: ‘, registration.scope); }).catch(function(err){ console.error(‘service worker registration failed: ‘, err); }); Get Server API key and Sender ID from GCM. Generating server key and sender id is simple go to GCM websites and follow the instructions or you can follow my video tutorial. Create a web manifest file. The web app manifest provides information about an application in a simple document. We have to add gcm_sender_id in manifest file for subscribing to GCM server. manifest.json 2/6
  • 3. { "name": "Web Push Demo", "short_name": "GCM Push", "icons": [{ "src": "images/icon-192x192.png", "sizes": "192x192", "type": "image/png" }], "start_url": "/index.html", "display": "standalone", "gcm_sender_id": "sender-id" } Subscribe to GCM for push messaging. Finally we have to subscribe to GCM server using subscribe() method on the PushManager object through the serviceWorkerRegistration object. navigator.serviceWorker.ready.then(function(serviceWorkerRegistration){ serviceWorkerRegistration.pushManger.subscribe({userVisibleOnly:true}) .then(function(subscription){ console.log(‘subscription successful: ‘, subscription); }).catch(function(err){ console.error(‘unable to subscribe to GCM’, err); }); }); Write some code for myworker.js myworker.js is the file which will be running in service worker thread of your web browser. Service worker is a javascript which is run by your browser in the background, write some code for receiving push message into your website. myworker.js self.addEventListener('push', function(event) { console.log('Push message received'); var notificationTitle = 'New Message'; const notificationOptions = { body: 'Push mesage received', icon: './images/icon-192x192.png', tag: 'simple-push-demo-notification', data: { url: 'http://ninjacoders.info' } }; event.waitUntil( Promise.all([ self.registration.showNotification( notificationTitle, notificationOptions) ]) ); }); Above code will register an event listener for push messages and whenever push message comes from GCM this event get triggered. 3/6
  • 4. self.addEventListener('notificationclick', function(event) { event.notification.close(); var clickResponsePromise = Promise.resolve(); if (event.notification.data && event.notification.data.url) { clickResponsePromise = clients.openWindow(event.notification.data.url); } event.waitUntil( Promise.all([ clickResponsePromise ]) ); }); Above code will register an event listener for notificationClick event and whenever user clicks on the notification window we will open a new web page. Integrate all peace of code. index.html 4/6
  • 5. <!DOCTYPE html> <html> <head> <title>Push Notification for Web Application</title> <link rel="manifest" href="/manifest.json"> <script> document.addEventListener('DOMContentLoaded', function() { document.querySelector("#enablepush") .addEventListener('click', function(e) { if(Notification.permission !== 'granted') { Notification.requestPermission().then(function(permission) { if(permission === 'granted' && 'serviceWorker' in navigator) { navigator.serviceWorker.register('myworker.js') .then(initialiseState); } else { console.log('service worker not present'); } }); } }); //get subscription token if already subscribed if(Notification.permission === 'granted') { navigator.serviceWorker.ready.then(function(registration) { registration.pushManager.getSubscription() .then(function(subscription){ getToken(subscription); }); }); } }); function initialiseState() { //check if notification is supported or not if(!('showNotification' in ServiceWorkerRegistration.prototype)) { console.warn('Notificaiton are not supported'); return; } //check if user has blocked push notification if(Notification.permission === 'denied'){ console.warn('User has blocked the notification'); } //check if push messaging is supported or not if(!('PushManager' in window)) { console.warn('Push messaging is not supported'); return; } //subscribe to GCM navigator.serviceWorker.ready .then(function(serviceWorkerRegistration) { //call subscribe method on serviceWorkerRegistration object serviceWorkerRegistration.pushManager .subscribe({userVisibleOnly: true}) .then(function(subscription){ getToken(subscription); }).catch(function(err){ console.error('Error occured while subscribe(): ', err); }); }); } function getToken(subscription) { console.log(subscription); var token = subscription.endpoint .substring(40, subscription.endpoint.length); document.querySelector("#token").innerHTML = token; } </script> </head> <body> <h1>Push Notification for Web Application</h1> <button id="enablepush">Enable Push</button><br /> <label for="token">Registration ID</label> <textarea id="token" rows="6" cols="40"></textarea> </body> </html> Send push message to Website. 5/6
  • 6. Sending push notification we use GCM, we have to send post request to GCM along with authorization key (Server Key) and client token (i.e registration id) https://gcm-http.googleapis.com/gcm/send Content-Type:application/json Authorization:key=AIzaSyZ-1u...fMwj0qwRt-bJvir { "data": { "message": "How to create PayPal", "url": "http://www.ninjacoders.info/" }, "to" : "fzeh02y7_p4:APA91bE-KxSmlLoJFyZftBlUkNsVXW..." } curl "https://android.googleapis.com/gcm/send" --request POST --header "Authorization: key=server_key" --header "Content-Type: application/json" -d "{"to":"client_token"}" For sending push messages to your website you have to make POST request from your server copy paste above 'curl' and place your server_key and client_token. You can also use this tool and enter your server_key and client_token click on send notification button. Note: HTTPS is needed to register service worker on production but you can test it without HTTPS on your local server url should be http://localhost You can use node http-server for deploy the app or you can use any server like wampp, xampp, lampp. Final Words: Integrate push notification in your website and engage more users. 6/6