8000 Add messaging sample · mlchiang/quickstart-js@c653e29 · GitHub
[go: up one dir, main page]

Skip to content

Commit c653e29

Browse files
committed
Add messaging sample
1 parent 1abb759 commit c653e29

File tree

6 files changed

+454
-0
lines changed

6 files changed

+454
-0
lines changed

messaging/README.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
Firebase Cloud Messaging Quickstart
2+
===================================
3+
4+
The Firebase Cloud Messaging quickstart demonstrates how to:
5+
- Request permission to send app notifications to the user.
6+
- Receive FCM messages using the Firebase Cloud Messaging JavaScript SDK.
7+
8+
Introduction
9+
------------
10+
11+
- [Read more about Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/)
12+< 8000 /span>
13+
Getting Started
14+
---------------
15+
16+
1. Set up your project on the [Firebase Console](https://console.firebase.google.com).
17+
2. Paste initialization snippet into `index.html` with the one generated from
18+
the Firebase Console **Overview > Add Firebase to your web app**. See TODO in
19+
`index.html`.
20+
3. Run the app
21+
- Install the [Firebase CLI](https://firebase.google.com/docs/cli/)
22+
- Use command `firebase serve -p 8081` to serve app locally.
23+
- Open http://localhost:8081 in your browser.
24+
4. Click REQUEST PERMISSION button to request permission for the app to send
25+
notifications to the browser.
26+
5. Use the generated Instance ID token to send an HTTP request to FCM that
27+
delivers the message to the web application, inserting appropriate values
28+
for YOUR-SERVER-KEY and YOUR-IID-TOKEN.
29+
### HTTP
30+
```
31+
POST /fcm/send HTTP/1.1
32+
Host: fcm.googleapis.com
33+
Authorization: key=YOUR-SERVER-KEY
34+
Content-Type: application/json
35+
36+
{
37+
"notification": {
38+
"title": "Portugal vs. Denmark",
39+
"body": "5 to 1",
40+
"icon": "firebase-icon.png",
41+
"click_action": "http://localhost:8081"
42+
},
43+
"to": "YOUR-IID-TOKEN"
44+
}
45+
```
46+
### cURL
47+
```
48+
curl -X POST -H "Authorization: key=YOUR-SERVER-KEY" -H "Content-Type: application/json" -d '{
49+
"notification": {
50+
"title": "Portugal vs. Denmark",
51+
"body": "5 to 1",
52+
"icon": "firebase-icon.png",
53+
"click_action": "http://localhost:8081"
9E88 54+
},
55+
"to": "YOUR-IID-TOKEN"
56+
}' "https://fcm.googleapis.com/fcm/send"
57+
```
58+
- When the app has the browser focus , the received message is handled through
59+
the `onMessage` callback in index.html. When the app does not have browser
60+
focus then the `setBackgroundMessageHandler` callback in firebase-messaging-sw.js
61+
is where the received message is handled.
62+
63+
### App focus
64+
The browser gives your app focus when both:
65+
1. Your app is running in the currently selected browser tab.
66+
2. The browser tab's window currently has focus, as defined by the operating system.
67+
68+
Support
69+
-------
70+
71+
https://firebase.google.com/support/
72+
73+
License
74+
-------
75+
76+
© Google, 2016. Licensed under an [Apache-2](../LICENSE) license.

messaging/firebase-logo.png

3.46 KB
Loading

messaging/firebase-messaging-sw.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// [START initialize_firebase_in_sw]
2+
// Give the service worker access to Firebase Messaging.
3+
// Note that you can only use Firebase Messaging here, other Firebase libraries
4+
// are not available in the service worker.
5+
importScripts('https://www.gstatic.com/firebasejs/3.5.0/firebase-app.js');
6+
importScripts('https://www.gstatic.com/firebasejs/3.5.0/firebase-messaging.js');
7+
8+
// Initialize the Firebase app in the service worker by passing in the
9+
// messagingSenderId.
10+
firebase.initializeApp({
11+
'messagingSenderId': 'YOUR-SENDER-ID'
12+
});
13+
14+
// Retrieve an instance of Firebase Messaging so that it can handle background
15+
// messages.
16+
const messaging = firebase.messaging();
17+
// [END initialize_firebase_in_sw]
18+
19+
// If you would like to customize notifications that are received in the
20+
// background (Web app is closed or not in browser focus) then you should
21+
// implement this optional method.
22+
// [START background_handler]
23+
messaging.setBackgroundMessageHandler(function(payload) {
24+
console.log('[firebase-messaging-sw.js] Received background message ', payload);
25+
// Customize notification here
26+
const notificationTitle = 'Background Message Title';
27+
const notificationOptions = {
28+
body: 'Background Message body.',
29+
icon: '/firebase-logo.png'
30+
};
31+
32+
return self.registration.showNotification(notificationTitle,
33+
notificationOptions);
34+
});
35+
// [END background_handler]

messaging/index.html

Lines changed: 284 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
1+
<!DOCTYPE html>
2+
<!--
3+
Copyright (c) 2016 Google Inc.
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
-->
17+
<html>
18+
<head>
19+
<meta charset=utf-8/>
20+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
21+
<title>Firebase Cloud Messaging Example</title>
22+
23+
<!-- Material Design Theming -->
24+
<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css">
25+
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
26+
<script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
27+
28+
<link rel="stylesheet" href="main.css">
29+
30+
<link rel="manifest" href="/manifest.json">
31+
</head>
32+
<body>
33+
<div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-header">
34+
35+
<!-- Header section containing title -->
36+
<header class="mdl-layout__header mdl-color-text--white mdl-color--light-blue-700">
37+
<div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-grid">
38+
<div class="mdl-layout__header-row mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--8-col-desktop">
39+
<h3>Firebase Cloud Messaging</h3>
40+
</div>
41+
</div>
42+
</header>
43+
44+
<main class="mdl-layout__content mdl-color--grey-100">
45+
<div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-grid">
46+
47+
<!-- Container for the Table of content -->
48+
<div class="mdl-card mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--12-col-desktop">
49+
<div class="mdl-card__supporting-text mdl-color-text--grey-600">
50+
<!-- div to display the generated Instance ID token -->
51+
<div id="token_div" style="display: none;">
52+
<h4>Instance ID Token</h4>
53+
<p id="token" style="word-break: break-all;"></p>
54+
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
55+
onclick="deleteToken()">Delete Token</button>
56+
</div>
57+
<!-- div to display the UI to allow the request for permission to
58+
notify the user. This is shown if the app has not yet been
59+
granted permission to notify. -->
60+
<div id="permission_div" style="display: none;">
61+
<h4>Needs Permission</h4>
62+
<p id="token"></p>
63+
<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
64+
onclick="requestPermission()">Request Permission</button>
65+
</div>
66+
<!-- div to display messages received by this app. -->
67+
<div id="messages"></div>
68+
</div>
69+
</div>
70+
71+
</div>
72+
</main>
73+
</div>
74+
<!-- Firebase -->
75+
<!-- ********************************************************
76+
* TODO(DEVELOPER): Update Firebase initialization code:
77+
1. Go to the Firebase console: https://console.firebase.google.com/
78+
2. Choose a Firebase project you've created
79+
3. Click "Add Firebase to your web app"
80+
4. Replace the following initialization code with the code from the Firebase console:
81+
-->
82+
<!-- START INITIALIZATION CODE -->
83+
<!-- PASTE FIREBASE INITIALIZATION CODE HERE -->
84+
<!-- END INITIALIZATION CODE -->
85+
<!-- ******************************************************** -->
86+
<script>
87+
// [START get_messaging_object]
88+
// Retrieve Firebase Messaging object.
89+
const messaging = firebase.messaging();
90+
// [END get_messaging_object]
91+
92+
// IDs of divs that display Instance ID token UI or request permission UI.
93+
const tokenDivId = 'token_div';
94+
const permissionDivId = 'permission_div';
95+
96+
// [START refresh_token]
97+
// Callback fired if Instance ID token is updated.
98+
messaging.onTokenRefresh(function() {
99+
messaging.getToken()
100+
.then(function(refreshedToken) {
101+
console.log('Token refreshed.');
102+
// Indicate that the new Instance ID token has not yet been sent to the
103+
// app server.
104+
setTokenSentToServer(false);
105+
// Send Instance ID token to app server.
106+
sendTokenToServer(refreshedToken);
107+
// [START_EXCLUDE]
108+
// Display new Instance ID token and clear UI of all previous messages.
109+
resetUI();
110+
// [END_EXCLUDE]
111+
})
112+
.catch(function(err) {
113+
console.log('Unable to retrieve refreshed token ', err);
114+
showToken('Unable to retrieve refreshed token ', err);
115+
});
116+
});
117+
// [END refresh_token]
118+
119+
// [START receive_message]
120+
// Handle incoming messages. Called when:
121+
// - a message is received while the app has focus
122+
// - the user clicks on an app notification created by a sevice worker
123+
// `messaging.setBackgroundMessageHandler` handler.
124+
messaging.onMessage(function(payload) {
125+
console.log("Message received. ", payload);
126+
// [START_EXCLUDE]
127+
// Update the UI to include the received message.
128+
appendMessage(payload);
129+
// [END_EXCLUDE]
130+
});
131+
// [END receive_message]
132+
133+
function resetUI() {
134+
clearMessages();
135+
showToken('loading...');
136+
// [START get_token]
137+
// Get Instance ID token. Initially this makes a network call, once retrieved
138+
// subsequent calls to getToken will return from cache.
139+
messaging.getToken()
140+
.then(function(currentToken) {
141+
if (currentToken) {
142+
sendTokenToServer(currentToken);
143+
updateUIForPushEnabled(currentToken);
144+
} else {
145+
// Show permission request.
146+
console.log('No Instance ID token available. Request permission to generate one.');
147+
// Show permission UI.
148+
updateUIForPushPermissionRequired();
149+
setTokenSentToServer(false);
150+
}
151+
})
152+
.catch(function(err) {
153+
console.log('An error occurred while retrieving token. ', err);
154+
showToken('Error retrieving Instance ID token. ', err);
155+
setTokenSentToServer(false);
156+
});
157+
}
158+
// [END get_token]
159+
160+
function showToken(currentToken) {
161+
// Show token in console and UI.
162+
var tokenElement = document.querySelector('#token');
163+
tokenElement.textContent = currentToken;
164+
}
165+
166+
// Send the Instance ID token your application server, so that it can:
167+
// - send messages back to this app
168+
// - subscribe/unsubscribe the token from topics
169+
function sendTokenToServer(currentToken) {
170+
if (!isTokenSentToServer()) {
171+
console.log('Sending token to server...');
172+
// TODO(developer): Send the current token to your server.
173+
setTokenSentToServer(true);
174+
} else {
175+
console.log('Token already sent to server so won\'t send it again ' +
176+
'unless it changes');
177+
}
178+
179+
}
180+
181+
function isTokenSentToServer() {
182+
if (window.localStorage.getItem('sentToServer') == 1) {
183+
return true;
184+
}
185+
return false;
186+
}
187+
188+
function setTokenSentToServer(sent) {
189+
if (sent) {
190+
window.localStorage.setItem('sentToServer', 1);
191+
} else {
192+
window.localStorage.setItem('sentToServer', 0);
193+
}
194+
}
195+
196+
function showHideDiv(divId, show) {
197+
const div = document.querySelector('#' + divId);
198+
if (show) {
199+
div.style = "display: visible";
200+
} else {
201+
div.style = "display: none";
202+
}
203+
}
204+
205+
function requestPermission() {
206+
console.log('Requesting permission...');
207+
// [START request_permission]
208+
messaging.requestPermission()
209+
.then(function() {
210+
console.log('Notification permission granted.');
211+
// TODO(developer): Retrieve a Instance ID token for use with FCM.
212+
// [START_EXCLUDE]
213+
// In many cases once an app has been granted notification permission, it
214+
// should update its UI reflecting this.
215+
resetUI();
216+
// [END_EXCLUDE]
217+
})
218+
.catch(function(err) {
219+
console.log('Unable to get permission to notify. ', err);
220+
});
221+
// [END request_permission]
222+
}
223+
224+
function deleteToken() {
225+
// Delete Instance ID token.
226+
// [START delete_token]
227+
messaging.getToken()
228+
.then(function(currentToken) {
229+
messaging.deleteToken(currentToken)
230+
.then(function() {
231+
console.log('Token deleted.');
232+
setTokenSentToServer(false);
233+
// [START_EXCLUDE]
234+
// Once token is deleted update UI.
235+
resetUI();
236+
// [END_EXCLUDE]
237+
})
238+
.catch(function(err) {
239+
console.log('Unable to delete token. ', err);
240+
});
241+
// [END delete_token]
242+
})
243+
.catch(function(err) {
244+
console.log('Error retrieving Instance ID token. ', err);
245+
showToken('Error retrieving Instance ID token. ', err);
246+
});
247+
248+
}
249+
250+
// Add a message to the messages element.
251+
function appendMessage(payload) {
252+
const messagesElement = document.querySelector('#messages');
253+
const dataHeaderELement = document.createElement('h5');
254+
const dataElement = document.createElement('pre');
255+
dataElement.style = 'overflow-x:hidden;'
256+
dataHeaderELement.textContent = 'Received message:';
257+
dataElement.textContent = JSON.stringify(payload, null, 2);
258+
messagesElement.appendChild(dataHeaderELement);
259+
messagesElement.appendChild(dataElement);
260+
}
261+
262+
// Clear the messages element of all children.
263+
function clearMessages() {
264+
const messagesElement = document.querySelector('#messages');
265+
while (messagesElement.hasChildNodes()) {
266+
messagesElement.removeChild(messagesElement.lastChild);
267+
}
268+
}
269+
270+
function updateUIForPushEnabled(currentToken) {
271+
showHideDiv(tokenDivId, true);
272+
showHideDiv(permissionDivId, false);
273+
showToken(currentToken);
274+
}
275+
276+
function updateUIForPushPermissionRequired() {
277+
showHideDiv(tokenDivId, false);
278+
showHideDiv(permissionDivId, true);
279+
}
280+
281+
resetUI();
282+
</script>
283+
</body>
284+
</html>

0 commit comments

Comments
 (0)
0