Skip to content

Commit 648134f

Browse files
authored
Merge pull request #567 from talkjs/feat/add-firebase-example
Add Firebase example
2 parents b011ced + 6d86069 commit 648134f

File tree

4 files changed

+329
-0
lines changed

4 files changed

+329
-0
lines changed

firebase/README.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
## How to send web push notifications to a browser with Firebase
2+
3+
This example project shows you how to send TalkJS's web push notifications to a browser with Firebase.
4+
5+
> [!TIP] > [Download this example project as a zip file](https://github.com/talkjs/talkjs-examples/releases/latest/download/firebase.notifications-example.zip)
6+
7+
## Prerequisites
8+
9+
To run this example project, you need:
10+
11+
- The [Firebase CLI](https://firebase.google.com/docs/cli#install_the_firebase_cli)
12+
- A [TalkJS account](https://talkjs.com/dashboard/login)
13+
14+
## How to run the example
15+
16+
1. Clone or [download this project](https://github.com/talkjs/talkjs-examples/releases/latest/download/firebase.notifications-example.zip).
17+
1. In the root directory of the project, run:
18+
```sh
19+
firebase login
20+
```
21+
if you are not already logged in, and log in to your account
22+
1. Set up Firebase hosting:
23+
```sh
24+
firebase init hosting
25+
```
26+
Select to either use an existing Firebase project or create a new one. If you create a new one, or you haven't yet set up Firebase Cloud Messaging in the TalkJS dashboard, see [Configure Firebase Cloud Messaging](https://talkjs.com/docs/Features/Notifications/Mobile_Push_Notifications/Configure_FCM/) in our docs.
27+
1. Answer the prompted questions:
28+
1. Select to use the default (`public`) as your public directory
29+
1. Select Yes for "Configure as a single-page app?"
30+
1. Choose whether to set up automatic builds and deploys with GitHub
31+
1. Select No for "File public/index.html already exists. Overwrite?"
32+
1. Once initialization is complete, open the [Firebase console](http://console.firebase.google.com/) and select your project.
33+
1. On the **Project Overview** page, click the **+** icon to add a new app. For the platform, select **Web**.
34+
1. Pick a name for your app.
35+
1. After registering the app name, you will see some code samples for adding the Firebase SDK. Copy the `firebaseConfig` JavaScript object. It will look something like this:
36+
```json
37+
{
38+
"apiKey": "<FIREBASE_API_KEY>",
39+
"authDomain": "<FIREBASE_APP_NAME>.firebaseapp.com",
40+
"projectId": "<FIREBASE_APP_NAME>",
41+
"storageBucket": "<FIREBASE_APP_NAME>.firebasestorage.app",
42+
"messagingSenderId": "<SENDER_ID>",
43+
"appId": "<FIREBASE_APP_ID>"
44+
}
45+
```
46+
1. Inside `public/index.html` (lines 168-175) and `public/firebase-messaging-sw.js` (lines 9-16), replace the placeholder object with your `firebaseConfig` object.
47+
1. In the Firebase console, click the gear icon and go to **Project Settings**. In the **Cloud Messaging** tab, go to the **Web configuration section** and then click **Generate Key Pair**.
48+
1. Copy the value under “Key Pair”. This is the public key used to encrypt web push notifications.
49+
1. Inside `public/index.html` (line 203), paste the value inside the string as the value for `vapidKey`.
50+
1. Inside `public/index.html`, replace `<APP_ID>` with your app ID, which you can find in the **Settings** tab of the [TalkJS dashboard](https://talkjs.com/dashboard).
51+
1. In the root directory of the project, run:
52+
```sh
53+
firebase deploy --only hosting
54+
```
55+
This will deploy the website at a URL like `https://<FIREBASE_APP_NAME>.web.app`.
56+
57+
## How to test the example
58+
59+
1. On the device where you want to receive push notifications, go to `https://<FIREBASE_APP_NAME>.web.app` and click the **Request token** button. Select to allow push notifications if prompted.
60+
1. Switch to a different tab with another site (this is so that a notification will trigger when you get a new message).
61+
1. Add a new message to the TalkJS `sample_conversation` conversation from the other user, `sample_user_alice`. A simple way to do this is to go to the **Chat UI** tab of the TalkJS dashboard](https://talkjs.com/dashboard) and add a message from the **Preview** chat UI.
62+
1. You should now receive a push notification to your device with the message text.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1">
6+
<title>Page Not Found</title>
7+
8+
<style media="screen">
9+
body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
10+
#message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px 16px; border-radius: 3px; }
11+
#message h3 { color: #888; font-weight: normal; font-size: 16px; margin: 16px 0 12px; }
12+
#message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
13+
#message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
14+
#message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
15+
#message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
16+
#message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
17+
#load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
18+
@media (max-width: 600px) {
19+
body, #message { margin-top: 0; background: white; box-shadow: none; }
20+
body { border-top: 16px solid #ffa100; }
21+
}
22+
</style>
23+
</head>
24+
<body>
25+
<div id="message">
26+
<h2>404</h2>
27+
<h1>Page Not Found</h1>
28+
<p>The specified file was not found on this website. Please check the URL for mistakes and try again.</p>
29+
<h3>Why am I seeing this?</h3>
30+
<p>This page was generated by the Firebase Command-Line Interface. To modify it, edit the <code>404.html</code> file in your project's configured <code>public</code> directory.</p>
31+
</div>
32+
</body>
33+
</html>
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
importScripts(
2+
"https://www.gstatic.com/firebasejs/11.1.0/firebase-app-compat.js"
3+
);
4+
importScripts(
5+
"https://www.gstatic.com/firebasejs/11.1.0/firebase-messaging-compat.js"
6+
);
7+
8+
// Update this with the firebaseConfig object from your Firebase app
9+
firebase.initializeApp({
10+
apiKey: "",
11+
authDomain: "",
12+
projectId: "",
13+
storageBucket: "",
14+
messagingSenderId: "",
15+
appId: "",
16+
});
17+
18+
// Retrieve an instance of Firebase Messaging so that it can handle background
19+
// messages.
20+
const messaging = firebase.messaging();
21+
22+
// Handle incoming messages. Called when:
23+
// - a message is received while the app has focus
24+
// - the user clicks on an app notification created by a service worker
25+
// `messaging.onBackgroundMessage` handler.
26+
messaging.onMessage((payload) => {
27+
console.log("Message received. ", payload);
28+
// ...
29+
});
30+
31+
messaging.onBackgroundMessage((payload) => {
32+
console.log(
33+
"[firebase-messaging-sw.js] Received background message ",
34+
payload
35+
);
36+
37+
const data = JSON.parse(payload.data["talkjs"]);
38+
console.log("TalkJS payload: ", data);
39+
40+
// Customize notification here
41+
const notificationTitle = `Message from ${data.sender.name}`;
42+
const notificationOptions = {
43+
body: data.message.text,
44+
icon: "/firebase-logo.png",
45+
};
46+
47+
self.registration.showNotification(notificationTitle, notificationOptions);
48+
});
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1" />
6+
<title>Example: TalkJS with Firebase Cloud Messaging notifications</title>
7+
8+
<script>
9+
(function (t, a, l, k, j, s) {
10+
s = a.createElement("script");
11+
s.async = 1;
12+
s.src = "https://cdn.talkjs.com/talk.js";
13+
a.head.appendChild(s);
14+
k = t.Promise;
15+
t.Talk = {
16+
v: 3,
17+
ready: {
18+
then: function (f) {
19+
if (k)
20+
return new k(function (r, e) {
21+
l.push([f, r, e]);
22+
});
23+
l.push([f]);
24+
},
25+
catch: function () {
26+
return k && new k();
27+
},
28+
c: l,
29+
},
30+
};
31+
})(window, document, []);
32+
</script>
33+
34+
<!-- update the version number as needed -->
35+
<script defer src="/__/firebase/11.1.0/firebase-app-compat.js"></script>
36+
<!-- include only the Firebase features as you need -->
37+
<script
38+
defer
39+
src="/__/firebase/11.1.0/firebase-messaging-compat.js"
40+
></script>
41+
42+
<style media="screen">
43+
body {
44+
/* background: white; */
45+
color: rgba(0, 0, 0, 0.87);
46+
font-family: Roboto, Helvetica, Arial, sans-serif;
47+
margin: 0;
48+
padding: 0;
49+
}
50+
.load {
51+
color: #525252;
52+
text-align: center;
53+
font-size: 13px;
54+
}
55+
#requestToken {
56+
margin: 0px 0px 12px;
57+
padding: 8px 16px;
58+
border-radius: 4px;
59+
background: #007df9;
60+
color: white;
61+
border: none;
62+
cursor: pointer;
63+
}
64+
@media (max-width: 600px) {
65+
body {
66+
margin-top: 0;
67+
background: white;
68+
box-shadow: none;
69+
}
70+
}
71+
</style>
72+
73+
<script>
74+
Talk.ready.then(function () {
75+
var me = new Talk.User({
76+
id: "sample_user_sebastian",
77+
name: "Sebastian",
78+
role: "default",
79+
});
80+
var other = new Talk.User({
81+
id: "sample_user_alice",
82+
name: "Alice",
83+
role: "default",
84+
});
85+
86+
window.talkSession = new Talk.Session({
87+
appId: "<APP_ID>", // update this with your TalkJS app ID
88+
me: me,
89+
});
90+
91+
var conversation = talkSession.getOrCreateConversation(
92+
"sample_conversation"
93+
);
94+
95+
conversation.setParticipant(me);
96+
conversation.setParticipant(other);
97+
98+
var chatbox = talkSession.createChatbox();
99+
100+
chatbox.select(conversation);
101+
chatbox.mount(document.getElementById("talkjs-container"));
102+
});
103+
</script>
104+
</head>
105+
<body>
106+
<p class="load" id="load">Firebase SDK loading&hellip;</p>
107+
<p class="load" id="token"></p>
108+
109+
<div style="display: flex; justify-content: center">
110+
<button id="requestToken">Request token</button>
111+
</div>
112+
113+
<div id="talkjs-container" style="height: 700px"></div>
114+
115+
<script>
116+
document.addEventListener("DOMContentLoaded", function () {
117+
const loadEl = document.querySelector("#load");
118+
// // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
119+
// // The Firebase SDK is initialized and available here!
120+
//
121+
// firebase.auth().onAuthStateChanged(user => { });
122+
// firebase.database().ref('/path/to/ref').on('value', snapshot => { });
123+
// firebase.firestore().doc('/foo/bar').get().then(() => { });
124+
// firebase.functions().httpsCallable('yourFunction')().then(() => { });
125+
// firebase.messaging().requestPermission().then(() => { });
126+
// firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
127+
// firebase.analytics(); // call to activate
128+
// firebase.analytics().logEvent('tutorial_completed');
129+
// firebase.performance(); // call to activate
130+
//
131+
// // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
132+
133+
try {
134+
// Update this with the firebaseConfig object from your Firebase app
135+
let app = firebase.initializeApp({
136+
apiKey: "",
137+
authDomain: "",
138+
projectId: "",
139+
storageBucket: "",
140+
messagingSenderId: "",
141+
appId: "",
142+
});
143+
let features = [
144+
"auth",
145+
"database",
146+
"firestore",
147+
"functions",
148+
"messaging",
149+
"storage",
150+
"analytics",
151+
"remoteConfig",
152+
"performance",
153+
].filter((feature) => typeof app[feature] === "function");
154+
loadEl.textContent = `Firebase SDK loaded with ${features.join(
155+
", "
156+
)}`;
157+
} catch (e) {
158+
console.error(e);
159+
loadEl.textContent =
160+
"Error loading the Firebase SDK, check the console.";
161+
}
162+
163+
const messaging = firebase.messaging(firebase.app());
164+
165+
document
166+
.getElementById("requestToken")
167+
.addEventListener("click", () => {
168+
messaging
169+
.getToken({
170+
vapidKey: "<FIREBASE_PUBLIC_KEY>", // update this with your Firebase project public key
171+
})
172+
.then((token) => {
173+
window.talkSession.setPushRegistration({
174+
provider: "fcm",
175+
pushRegistrationId: token,
176+
});
177+
178+
document.getElementById(
179+
"token"
180+
).textContent = `Got token: ${token.substring(0, 16)}...`;
181+
});
182+
});
183+
});
184+
</script>
185+
</body>
186+
</html>

0 commit comments

Comments
 (0)