-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIterableWebPush.html
More file actions
244 lines (223 loc) · 8.92 KB
/
IterableWebPush.html
File metadata and controls
244 lines (223 loc) · 8.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.7.2/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.2/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
apiKey: "<FIREBASE_WEB_API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<PROJECT_ID>.appspot.com",
messagingSenderId: "<FIREBASE_SENDER_ID>",
};
var iterable_apiKey = "<ITERABLE_API_KEY>"
var email = "<USER_EMAIL>"
var usePublicVapidKey = '<FIREBASE_WEBPUSH_CERTIFICATE>'
firebase.initializeApp(config);
</script>
<!-- ITERABLE MUST HAVE -->
<!-- ITERABLE MUST HAVE -->
<script>
// [START get_messaging_object]
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// [END get_messaging_object]
// [START set_public_vapid_key]
// Add the public key generated from the console here.
//////////FIREBSE MUST HAVE ////////////
messaging.usePublicVapidKey(String(usePublicVapidKey));
console.log('usePublicVapidKey!!!!!!...' + usePublicVapidKey)
// [END set_public_vapid_key]
//////////FIREBSE MUST HAVE ////////////
// IDs of divs that display Instance ID token UI or request permission UI.
const tokenDivId = 'token_div';
const permissionDivId = 'permission_div';
// [START request_permission]
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// [START_EXCLUDE]
// In many cases once an app has been granted notification permission, it
// should update its UI reflecting this.
resetUI();
// [END_EXCLUDE]
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
// [START receive_message]
// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
// [START_EXCLUDE]
// Update the UI to include the received message.
appendMessage(payload);
var campaignId_integer = parseInt(payload.data.campaignId, 10);
var templateId_integer = parseInt(payload.data.templateId, 10);
var track_web_url = "https://api.iterable.com/api/events/trackWebPushClick";
var method = "POST";
var postData = {
'email': String(email),
'messageId': payload.data.messageId,
'campaignId': campaignId_integer,
'templateId': templateId_integer
};
console.log('postData!!!!!!...' + postData);
var async = true;
var request = new XMLHttpRequest();
request.open(method, track_web_url, async);
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Api-Key', String(iterable_apiKey));
request.send(JSON.stringify(postData));
request.onreadystatechange=(e)=>{
console.log('Track push to Iterable...' + request.responseText)
}
});
// [END receive_message]
function resetUI() {
clearMessages();
showToken('loading...');
// [START get_token]
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then(function(currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
// [END get_token]
}
function showToken(currentToken) {
// Show token in console and UI.
var tokenElement = document.querySelector('#token');
tokenElement.textContent = currentToken;
console.log(currentToken);
}
// Send the Instance ID token your application server, so that it can:
// - send messages back to this app
// - subscribe/unsubscribe the token from topics
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
/////////// ITERABLE MUST HAVE ////////////////
console.log('Sending token to Iterable...');
var browser_register_url = "https://api.iterable.com/api/users/registerBrowserToken";
var method = "POST";
var postData = {
'email': String(email),
'browserToken': currentToken,
'userId': '',
};
var async = true;
var request = new XMLHttpRequest();
request.open(method, browser_register_url, async);
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Api-Key', String(iterable_apiKey));
request.send(JSON.stringify(postData));
// console.log('Response from Iterable...');
request.onreadystatechange=(e)=>{
console.log('Response from Iterable...' + request.responseText)
}
/////////// ITERABLE MUST HAVE ////////////////
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') === '1';
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}
function showHideDiv(divId, show) {
const div = document.querySelector('#' + divId);
if (show) {
div.style = 'display: visible';
} else {
div.style = 'display: none';
}
}
function requestPermission() {
console.log('Requesting permission...');
// [START request_permission]
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// [START_EXCLUDE]
// In many cases once an app has been granted notification permission, it
// should update its UI reflecting this.
resetUI();
// [END_EXCLUDE]
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
// [END request_permission]
}
function deleteToken() {
console.log('email!!!!!!...' + email);
// Delete Instance ID token.
// [START delete_token]
messaging.getToken().then(function(currentToken) {
messaging.deleteToken(currentToken).then(function() {
console.log('Token deleted.');
setTokenSentToServer(false);
// [START_EXCLUDE]
// Once token is deleted update UI.
resetUI();
// [END_EXCLUDE]
}).catch(function(err) {
console.log('Unable to delete token. ', err);
});
// [END delete_token]
}).catch(function(err) {
console.log('Error retrieving Instance ID token. ', err);
showToken('Error retrieving Instance ID token. ', err);
});
}
// Add a message to the messages element.
function appendMessage(payload) {
const messagesElement = document.querySelector('#messages');
const dataHeaderELement = document.createElement('h5');
const dataElement = document.createElement('pre');
dataElement.style = 'overflow-x:hidden;';
dataHeaderELement.textContent = 'Received message:';
dataElement.textContent = JSON.stringify(payload, null, 2);
messagesElement.appendChild(dataHeaderELement);
messagesElement.appendChild(dataElement);
}
// Clear the messages element of all children.
function clearMessages() {
const messagesElement = document.querySelector('#messages');
while (messagesElement.hasChildNodes()) {
messagesElement.removeChild(messagesElement.lastChild);
}
}
function updateUIForPushEnabled(currentToken) {
// showHideDiv(tokenDivId, true);
// showHideDiv(permissionDivId, false);
showToken(currentToken);
}
function updateUIForPushPermissionRequired() {
// showHideDiv(tokenDivId, false);
// showHideDiv(permissionDivId, true);
}
resetUI();
</script>
</body>
</html>