SlideShare a Scribd company logo
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

More Related Content

Recently uploaded

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 
Intelligent Gimbal FINAL PAPER Engineering.pdf
Intelligent Gimbal FINAL PAPER Engineering.pdfIntelligent Gimbal FINAL PAPER Engineering.pdf
Intelligent Gimbal FINAL PAPER Engineering.pdfAnthony Lucente
 
Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Boni Yeamin
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekCzechDreamin
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...CzechDreamin
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIES VE
 
Motion for AI: Creating Empathy in Technology
Motion for AI: Creating Empathy in TechnologyMotion for AI: Creating Empathy in Technology
Motion for AI: Creating Empathy in TechnologyUXDXConf
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessUXDXConf
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 

Recently uploaded (20)

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Intelligent Gimbal FINAL PAPER Engineering.pdf
Intelligent Gimbal FINAL PAPER Engineering.pdfIntelligent Gimbal FINAL PAPER Engineering.pdf
Intelligent Gimbal FINAL PAPER Engineering.pdf
 
Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Motion for AI: Creating Empathy in Technology
Motion for AI: Creating Empathy in TechnologyMotion for AI: Creating Empathy in Technology
Motion for AI: Creating Empathy in Technology
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 

Featured

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 2024Albert Qian
 
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 InsightsKurio // The Social Media Age(ncy)
 
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 2024Search Engine Journal
 
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 summarySpeakerHub
 
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 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 Tessa Mero
 
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 IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
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 managementMindGenius
 
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...RachelPearson36
 
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...Applitools
 
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 WorkGetSmarter
 
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...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 
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 wellSaba Software
 
Introduction to C Programming Language
Introduction to C Programming LanguageIntroduction to C Programming Language
Introduction to C Programming LanguageSimplilearn
 

Featured (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