SlideShare una empresa de Scribd logo
1 de 35
IndexedDB and Push
Notifications in Progressive
Web Apps
Adegoke Obasa
What you’ll learn - IndexedDB
Create an indexed database.
Create object stores.
Store data in the object stores.
Retrieve data from the object stores.
Update and delete data from the object stores.
What you’ll learn - Push Notifications
How to set up a Firebase Cloud Messaging (FCM) account
Techniques for requesting GCM to send a notification to a web client
Notification display
Notification click handling
What you’ll need
Chrome 42 or above
A basic understanding of git, and Chrome DevTools
Experience of service worker would also be useful, but is not crucial
The sample code
A text editor
Python or a simple local web server.
IndexedDB
What is IndexedDB?
Why IndexedDB?
Pros of IndexedDB
It stores the data as Key-Pair values.
It is asynchronous.
It is non relational.
Can access the data from the same domain.
It allows indexed database queries.
IndexedDB Support
“Talk is cheap, show me the code”
- Linus Torvalds
IndexedDB 101
IndexedDB Support
Method 1
Open the Chrome Developer Tools
Switch to the Console
Run `indexedDB`command
Method 2
Go to the Application tab
Method 1
Method 2
Todo App
Clone - https://github.com/goke-epapa/indexed-db-and-push-notifications
Switch to the indexed-db-starter branch
git reset --hard
git checkout indexed-db-starter
Create Database
and object store
Add code to js/idb.js file
var dbEngine = indexedDB.open(dbName, dbVersion);
dbEngine.onupgradeneeded = function (event) {
log("That's cool, we are upgrading");
// Create ObjectStore
var db = event.target.result;
if (!db.objectStoreNames.contains(TODO_STORE)) {
var objectStore = db.createObjectStore(TODO_STORE,
{keyPath: "id", autoIncrement: true});
}
};
Add todo
Add code to js/idb.js file
var engine = indexedDB.open(dbName, dbVersion);
engine.onsuccess = function (event) {
var db = event.target.result;
var transaction = db.transaction([TODO_STORE], "readwrite");
var store = transaction.objectStore(TODO_STORE);
var request = store.add(todo);
request.onsuccess = function (e) {
log('TODO inserted >> ', e.target.result);
};
request.error = function (e) {
error('An error occurred');
};
};
engine.onerror = function (error) {
error('An error occured ', error);
};
Clear all todos
Add code to js/idb.js file
var engine = indexedDB.open(dbName, dbVersion);
engine.onsuccess = function (event) {
var db = event.target.result;
var transaction = db.transaction([TODO_STORE], "readwrite");
var store = transaction.objectStore(TODO_STORE);
var request = store.clear();
request.onsuccess = function (e) {
log('All todos deleted');
};
request.error = function (e) {
error('An error occurred);
};
};
engine.onerror = function (error) {
error('An error occured ', error);
};
Render todos
Add code to js/idb.js file
...
store.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if(cursor) {
// Renders todo
log(cursor.value);
renderTodocallback(cursor.value);
cursor.continue();
} else {
log('All todos fetched');
}
};
};
...
Delete todo
Add code to js/idb.js file
...
var transaction = db.transaction([TODO_STORE], "readwrite");
var store = transaction.objectStore(TODO_STORE);
var request = store.delete(Number(id));
request.onsuccess = function (e) {
log('Todo ' + id + 'deleted');
if (typeof callback != 'undefined') {
callback();
}
};
request.error = function (e) {
error('An error occurred');
};
...
Push Notifications
Implementing Push Notifications in the
Todo App
Switch to the push-notifications-starter branch
git reset --hard
git checkout push-notifications-starter
Create a Firebase
Cloud Messaging
(FCM ) project.
Navigate to the Google Developers
Console -
https://console.cloud.google.com
Enable FCM
From Use Google APIs, select
Enable and manage APIs
From the Google APIs list, select
Google Cloud Messaging
Click the Enable button
Get credentials
From the API Manager menu,
select Credentials
Click the Create credentials
dropdown button and select
API key:
Click the Go to Credentials button
For Where will you be calling the
API from? Select Web Browser
(Javascript)
Click the What Credentials do I
need button
Give the key a name (anything you
Update Manifest
Add gcm_sender_id to the
manifest.json file. The gcm_sender_id
value should be the Project Number
you saved earlier.
{
"short_name" : "GDG Ibadan",
"name" : "GDG Ibadan",
"icons" : [
{
"src" : "/img/nn.min.png",
"sizes" : "192x192",
"type" : "image/png"
}
],
"start_url" : "/",
"display" : "standalone",
"theme_color" : "#666",
"background_color" : "#666",
"gcm_sender_id": "**************"
}
Set Variables
Add the code to js/app.js file in the
immediately after // TODO Set
subscribe button disabled
attribute to false
reg = serviceWorkerRegistration;
subscribeButton.disabled = false;
Add Subscription
Code
Add the code to js/app.js file
reg.pushManager.subscribe({
userVisibleOnly: true
}).then(function (pushSubscription) {
sub = pushSubscription;
console.log('Subscribed! endpoint:', sub.endpoint);
subscribeButton.textContent = 'Unsubscribe';
isSubscribed = true;
})
Add
Unsubscription
Code
Add the code to js/app.js file
sub.unsubscribe().then(function (event) {
subscribeButton.textContent = 'Subscribe';
console.log('Unsubscribed!', event);
isSubscribed = false;
}).catch(function (error) {
console.log('Error unubscribing', error);
subscribeButton.textContent = 'Subscribe';
})
Get Subscription ID
Open the Chrome Developer Tools
and switch to Console
Click on the Subscribe button
Right click on the link in the
console and copy it
The subscription ID is the part after
the last slash in the url
Usually looks like this:
eRiejdjxANbd_aY:APA91bFx_ZbfwOMbwL7hHVomb-
47EMwDGTxOKTnf1JJEgj9nWxZ_yr7lLqwBtj_P_JZsEHjVCcw
leVKnNEJpLVUYjejfIvSD9Y1WFhvsp4ic8wUxloqaPnZwUMRB
-dJbOsDPm48biXYvshdhj
Send GCM Push
message request
Using curl or any HTTP Client
Sample command using curl:
curl --header "Authorization: key=XXXXXXXXXXXX" -
-header "Content-Type: application/json"
https://android.googleapis.com/gcm/send -d
"{"registration_ids":["fs...Tw:APA...SzXha"]}
"
Show Notification
Add the code to sw.js file
self.addEventListener('push', function (event) {
console.log('Push message received', event);
var title = 'Push Message';
// Show notification
event.waitUntil(
self.registration.showNotification(title, {
body: 'The Message',
icon: 'img/nn.min.png',
tag: 'my-tag'
})
);
});
Handle notification
clicks
Add the code to sw.js file
self.addEventListener('notificationclick', function (event) {
event.notification.close();
var url = 'https://attending.io/events/buildpwa-v2';
event.waitUntil(
clients.matchAll({
type: 'window'
}).then(function (windowClients) {
windowClients.forEach(function (client) {
if (client.url == url && 'focus' in client) {
return client.focus();
}
});
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
Pat yourself on the back. You
built a web app that enables
Push Notifications!
References
Google Developers - Your First Push Notifications Web App
Further Reading / Recommendations
Udacity Course - Offline Web Applications
Thanks!
Adegoke Obasa
Software Engineer
Cotta & Cush Limited | adKandi
@goke_epapa
www.adegokeobasa.me

Más contenido relacionado

La actualidad más candente

Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banksGrokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banksGrokking VN
 
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018HashiCorp
 
Making sense of microservices, service mesh, and serverless
Making sense of microservices, service mesh, and serverlessMaking sense of microservices, service mesh, and serverless
Making sense of microservices, service mesh, and serverlessChristian Posta
 
NServiceBus - introduction to a message based distributed architecture
NServiceBus - introduction to a message based distributed architectureNServiceBus - introduction to a message based distributed architecture
NServiceBus - introduction to a message based distributed architectureMauro Servienti
 
Rà soát Malware bằng SysInternal Suite
Rà soát Malware bằng SysInternal SuiteRà soát Malware bằng SysInternal Suite
Rà soát Malware bằng SysInternal SuitePhạm Trung Đức
 
DDosMon A Global DDoS Monitoring Project
DDosMon A Global DDoS Monitoring ProjectDDosMon A Global DDoS Monitoring Project
DDosMon A Global DDoS Monitoring ProjectAPNIC
 
How to do Cryptography right in Android Part Two
How to do Cryptography right in Android Part TwoHow to do Cryptography right in Android Part Two
How to do Cryptography right in Android Part TwoArash Ramez
 
The role of_accreditation_in_conformity_assessment_in_digital_society
The role of_accreditation_in_conformity_assessment_in_digital_societyThe role of_accreditation_in_conformity_assessment_in_digital_society
The role of_accreditation_in_conformity_assessment_in_digital_societyToru Yamauchi
 
CS6701 CRYPTOGRAPHY AND NETWORK SECURITY
CS6701 CRYPTOGRAPHY AND NETWORK SECURITYCS6701 CRYPTOGRAPHY AND NETWORK SECURITY
CS6701 CRYPTOGRAPHY AND NETWORK SECURITYKathirvel Ayyaswamy
 
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...Andrey Devyatkin
 

La actualidad más candente (12)

Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banksGrokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
Grokking Techtalk #46: Lessons from years hacking and defending Vietnamese banks
 
C++ metaprogramming
C++ metaprogrammingC++ metaprogramming
C++ metaprogramming
 
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
Eliminating Secret Sprawl in the Cloud with HashiCorp Vault - 07.11.2018
 
Making sense of microservices, service mesh, and serverless
Making sense of microservices, service mesh, and serverlessMaking sense of microservices, service mesh, and serverless
Making sense of microservices, service mesh, and serverless
 
NServiceBus - introduction to a message based distributed architecture
NServiceBus - introduction to a message based distributed architectureNServiceBus - introduction to a message based distributed architecture
NServiceBus - introduction to a message based distributed architecture
 
Rà soát Malware bằng SysInternal Suite
Rà soát Malware bằng SysInternal SuiteRà soát Malware bằng SysInternal Suite
Rà soát Malware bằng SysInternal Suite
 
DDosMon A Global DDoS Monitoring Project
DDosMon A Global DDoS Monitoring ProjectDDosMon A Global DDoS Monitoring Project
DDosMon A Global DDoS Monitoring Project
 
How to do Cryptography right in Android Part Two
How to do Cryptography right in Android Part TwoHow to do Cryptography right in Android Part Two
How to do Cryptography right in Android Part Two
 
The role of_accreditation_in_conformity_assessment_in_digital_society
The role of_accreditation_in_conformity_assessment_in_digital_societyThe role of_accreditation_in_conformity_assessment_in_digital_society
The role of_accreditation_in_conformity_assessment_in_digital_society
 
CS6701 CRYPTOGRAPHY AND NETWORK SECURITY
CS6701 CRYPTOGRAPHY AND NETWORK SECURITYCS6701 CRYPTOGRAPHY AND NETWORK SECURITY
CS6701 CRYPTOGRAPHY AND NETWORK SECURITY
 
Netflix conductor
Netflix conductorNetflix conductor
Netflix conductor
 
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
 

Similar a IndexedDB and Push Notifications in Progressive Web Apps

Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps OfflinePedro Morais
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Python Ireland
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code維佋 唐
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup PerformanceGreg Whalin
 
Introduction To Code Igniter
Introduction To Code IgniterIntroduction To Code Igniter
Introduction To Code IgniterAmzad Hossain
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slideshelenmga
 
Introduction to Spring Boot.pdf
Introduction to Spring Boot.pdfIntroduction to Spring Boot.pdf
Introduction to Spring Boot.pdfShaiAlmog1
 
OpenCms Days 2014 - User Generated Content in OpenCms 9.5
OpenCms Days 2014 - User Generated Content in OpenCms 9.5OpenCms Days 2014 - User Generated Content in OpenCms 9.5
OpenCms Days 2014 - User Generated Content in OpenCms 9.5Alkacon Software GmbH & Co. KG
 
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...Amazon Web Services
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRVue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRJavier Abadía
 
Sebastian Schmidt, Rachel Myers - How To Go Serverless And Not Violate The GD...
Sebastian Schmidt, Rachel Myers - How To Go Serverless And Not Violate The GD...Sebastian Schmidt, Rachel Myers - How To Go Serverless And Not Violate The GD...
Sebastian Schmidt, Rachel Myers - How To Go Serverless And Not Violate The GD...Codemotion
 

Similar a IndexedDB and Push Notifications in Progressive Web Apps (20)

Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
IOC + Javascript
IOC + JavascriptIOC + Javascript
IOC + Javascript
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
 
前端概述
前端概述前端概述
前端概述
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
Html indexed db
Html indexed dbHtml indexed db
Html indexed db
 
Introduction To Code Igniter
Introduction To Code IgniterIntroduction To Code Igniter
Introduction To Code Igniter
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
 
Introduction to Spring Boot.pdf
Introduction to Spring Boot.pdfIntroduction to Spring Boot.pdf
Introduction to Spring Boot.pdf
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
OpenCms Days 2014 - User Generated Content in OpenCms 9.5
OpenCms Days 2014 - User Generated Content in OpenCms 9.5OpenCms Days 2014 - User Generated Content in OpenCms 9.5
OpenCms Days 2014 - User Generated Content in OpenCms 9.5
 
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
 
End-to-end testing with geb
End-to-end testing with gebEnd-to-end testing with geb
End-to-end testing with geb
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRVue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMR
 
Sebastian Schmidt, Rachel Myers - How To Go Serverless And Not Violate The GD...
Sebastian Schmidt, Rachel Myers - How To Go Serverless And Not Violate The GD...Sebastian Schmidt, Rachel Myers - How To Go Serverless And Not Violate The GD...
Sebastian Schmidt, Rachel Myers - How To Go Serverless And Not Violate The GD...
 

Último

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, Adobeapidays
 
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...apidays
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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 businesspanagenda
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
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)Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
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 SavingEdi Saputra
 

Último (20)

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
 
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...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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)
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
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
 

IndexedDB and Push Notifications in Progressive Web Apps

  • 1. IndexedDB and Push Notifications in Progressive Web Apps Adegoke Obasa
  • 2. What you’ll learn - IndexedDB Create an indexed database. Create object stores. Store data in the object stores. Retrieve data from the object stores. Update and delete data from the object stores.
  • 3. What you’ll learn - Push Notifications How to set up a Firebase Cloud Messaging (FCM) account Techniques for requesting GCM to send a notification to a web client Notification display Notification click handling
  • 4. What you’ll need Chrome 42 or above A basic understanding of git, and Chrome DevTools Experience of service worker would also be useful, but is not crucial The sample code A text editor Python or a simple local web server.
  • 8. Pros of IndexedDB It stores the data as Key-Pair values. It is asynchronous. It is non relational. Can access the data from the same domain. It allows indexed database queries.
  • 10. “Talk is cheap, show me the code” - Linus Torvalds
  • 12. IndexedDB Support Method 1 Open the Chrome Developer Tools Switch to the Console Run `indexedDB`command Method 2 Go to the Application tab Method 1 Method 2
  • 13. Todo App Clone - https://github.com/goke-epapa/indexed-db-and-push-notifications Switch to the indexed-db-starter branch git reset --hard git checkout indexed-db-starter
  • 14. Create Database and object store Add code to js/idb.js file var dbEngine = indexedDB.open(dbName, dbVersion); dbEngine.onupgradeneeded = function (event) { log("That's cool, we are upgrading"); // Create ObjectStore var db = event.target.result; if (!db.objectStoreNames.contains(TODO_STORE)) { var objectStore = db.createObjectStore(TODO_STORE, {keyPath: "id", autoIncrement: true}); } };
  • 15. Add todo Add code to js/idb.js file var engine = indexedDB.open(dbName, dbVersion); engine.onsuccess = function (event) { var db = event.target.result; var transaction = db.transaction([TODO_STORE], "readwrite"); var store = transaction.objectStore(TODO_STORE); var request = store.add(todo); request.onsuccess = function (e) { log('TODO inserted >> ', e.target.result); }; request.error = function (e) { error('An error occurred'); }; }; engine.onerror = function (error) { error('An error occured ', error); };
  • 16. Clear all todos Add code to js/idb.js file var engine = indexedDB.open(dbName, dbVersion); engine.onsuccess = function (event) { var db = event.target.result; var transaction = db.transaction([TODO_STORE], "readwrite"); var store = transaction.objectStore(TODO_STORE); var request = store.clear(); request.onsuccess = function (e) { log('All todos deleted'); }; request.error = function (e) { error('An error occurred); }; }; engine.onerror = function (error) { error('An error occured ', error); };
  • 17. Render todos Add code to js/idb.js file ... store.openCursor().onsuccess = function (event) { var cursor = event.target.result; if(cursor) { // Renders todo log(cursor.value); renderTodocallback(cursor.value); cursor.continue(); } else { log('All todos fetched'); } }; }; ...
  • 18. Delete todo Add code to js/idb.js file ... var transaction = db.transaction([TODO_STORE], "readwrite"); var store = transaction.objectStore(TODO_STORE); var request = store.delete(Number(id)); request.onsuccess = function (e) { log('Todo ' + id + 'deleted'); if (typeof callback != 'undefined') { callback(); } }; request.error = function (e) { error('An error occurred'); }; ...
  • 20. Implementing Push Notifications in the Todo App Switch to the push-notifications-starter branch git reset --hard git checkout push-notifications-starter
  • 21. Create a Firebase Cloud Messaging (FCM ) project. Navigate to the Google Developers Console - https://console.cloud.google.com
  • 22. Enable FCM From Use Google APIs, select Enable and manage APIs From the Google APIs list, select Google Cloud Messaging Click the Enable button
  • 23. Get credentials From the API Manager menu, select Credentials Click the Create credentials dropdown button and select API key: Click the Go to Credentials button For Where will you be calling the API from? Select Web Browser (Javascript) Click the What Credentials do I need button Give the key a name (anything you
  • 24. Update Manifest Add gcm_sender_id to the manifest.json file. The gcm_sender_id value should be the Project Number you saved earlier. { "short_name" : "GDG Ibadan", "name" : "GDG Ibadan", "icons" : [ { "src" : "/img/nn.min.png", "sizes" : "192x192", "type" : "image/png" } ], "start_url" : "/", "display" : "standalone", "theme_color" : "#666", "background_color" : "#666", "gcm_sender_id": "**************" }
  • 25. Set Variables Add the code to js/app.js file in the immediately after // TODO Set subscribe button disabled attribute to false reg = serviceWorkerRegistration; subscribeButton.disabled = false;
  • 26. Add Subscription Code Add the code to js/app.js file reg.pushManager.subscribe({ userVisibleOnly: true }).then(function (pushSubscription) { sub = pushSubscription; console.log('Subscribed! endpoint:', sub.endpoint); subscribeButton.textContent = 'Unsubscribe'; isSubscribed = true; })
  • 27. Add Unsubscription Code Add the code to js/app.js file sub.unsubscribe().then(function (event) { subscribeButton.textContent = 'Subscribe'; console.log('Unsubscribed!', event); isSubscribed = false; }).catch(function (error) { console.log('Error unubscribing', error); subscribeButton.textContent = 'Subscribe'; })
  • 28. Get Subscription ID Open the Chrome Developer Tools and switch to Console Click on the Subscribe button Right click on the link in the console and copy it The subscription ID is the part after the last slash in the url Usually looks like this: eRiejdjxANbd_aY:APA91bFx_ZbfwOMbwL7hHVomb- 47EMwDGTxOKTnf1JJEgj9nWxZ_yr7lLqwBtj_P_JZsEHjVCcw leVKnNEJpLVUYjejfIvSD9Y1WFhvsp4ic8wUxloqaPnZwUMRB -dJbOsDPm48biXYvshdhj
  • 29. Send GCM Push message request Using curl or any HTTP Client Sample command using curl: curl --header "Authorization: key=XXXXXXXXXXXX" - -header "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{"registration_ids":["fs...Tw:APA...SzXha"]} "
  • 30. Show Notification Add the code to sw.js file self.addEventListener('push', function (event) { console.log('Push message received', event); var title = 'Push Message'; // Show notification event.waitUntil( self.registration.showNotification(title, { body: 'The Message', icon: 'img/nn.min.png', tag: 'my-tag' }) ); });
  • 31. Handle notification clicks Add the code to sw.js file self.addEventListener('notificationclick', function (event) { event.notification.close(); var url = 'https://attending.io/events/buildpwa-v2'; event.waitUntil( clients.matchAll({ type: 'window' }).then(function (windowClients) { windowClients.forEach(function (client) { if (client.url == url && 'focus' in client) { return client.focus(); } }); if (clients.openWindow) { return clients.openWindow(url); } }) ); });
  • 32. Pat yourself on the back. You built a web app that enables Push Notifications!
  • 33. References Google Developers - Your First Push Notifications Web App
  • 34. Further Reading / Recommendations Udacity Course - Offline Web Applications
  • 35. Thanks! Adegoke Obasa Software Engineer Cotta & Cush Limited | adKandi @goke_epapa www.adegokeobasa.me

Notas del editor

  1. An IndexedDB is basically a persistent data store in the browser—a database on the client side. Like regular relational databases, it maintains indexes over the records it stores and developers use the IndexedDB JavaScript API to locate records by key or by looking up an index. Why does IndexedDB have such a bad reputation? The API is often horrid and often creates spaghetti code. It predates promises, so it kind of invented its own event-based promise system. It mirrors IndexedDB API, but uses promises rather than events. It pretty much the same as IndexedDB. https://github.com/jakearchibald/indexeddb-promised
  2. It allows for multiple databases with whatever name you give them. A single database can contain multiple object stores, generally one for each object you want to store. An objects store contains multiple values, this can be javascript objects, numbers, strings, dates or arrays. Items in the object store can have a separate primary key, or you can assign a property of the values to be the key. Keys must be unique in an object store, as it is the way to identify.
  3. Local Storage and Session Storage - Store Strings - You always need to JSON stringify IndexedDB vs WebSQL - WebSQL has been deprecated since November 18, 2010
  4. http://caniuse.com/#feat=indexeddb
  5. Image credits: http://blog.andromo.com/2012/introducing-airbop-push-notification-service-for-android/
  6. Get the API key — you’ll need this later: From the Home page, get the Project Number — you’ll also need this later:
  7. You must pass a {userVisibleOnly: true} argument to the subscribe() method. This tells the browser that a notification will always be shown when a push message is received. Currently it’s mandatory to show a notification.
  8. You must pass a {userVisibleOnly: true} argument to the subscribe() method. This tells the browser that a notification will always be shown when a push message is received. Currently it’s mandatory to show a notification.
  9. Ensure you check update on reload in service worker tab to ensure
  10. Ensure you check update on reload in service worker tab to ensure. NOTE: Android doesn’t close the notification when you click it. That’s why we need event.notification.close(); This code listens for a notification click, then opens a web page — in this example, a YouTube video. 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.