UNPKG

20.7 kBMarkdownView Raw
1# API
2
3- [.init()](#pushnotificationinitoptions)
4- [.hasPermission()](#pushnotificationhaspermissionsuccesshandler)
5- [.createChannel() - Android only](#pushnotificationcreatechannel)
6- [.deleteChannel() - Android only](#pushnotificationdeletechannel)
7- [.listChannels() - Android only](#pushnotificationlistchannels)
8- [push.on()](#pushonevent-callback)
9 - [push.on('registration')](#pushonregistration-callback)
10 - [push.on('notification')](#pushonnotification-callback)
11 - [push.on('error')](#pushonerror-callback)
12- [push.off()](#pushoffevent-callback)
13- [push.unregister()](#pushunregistersuccesshandler-errorhandler-topics)
14- [push.subscribe()](#pushsubscribetopic-successhandler-errorhandler)
15- [push.unsubscribe()](#pushunsubscribetopic-successhandler-errorhandler)
16- [push.setApplicationIconBadgeNumber() - iOS & Android only](#pushsetapplicationiconbadgenumbersuccesshandler-errorhandler-count---ios--android-only)
17- [push.getApplicationIconBadgeNumber() - iOS & Android only](#pushgetapplicationiconbadgenumbersuccesshandler-errorhandler---ios--android-only)
18- [push.finish() - iOS only](#pushfinishsuccesshandler-errorhandler-id---ios-only)
19- [push.clearAllNotifications() - iOS & Android only](#pushclearallnotificationssuccesshandler-errorhandler---ios--android-only)
20
21## PushNotification.init(options)
22
23Initializes the plugin on the native side.
24
25**Note:** like all plugins you must wait until you receive the [`deviceready`](https://cordova.apache.org/docs/en/5.4.0/cordova/events/events.deviceready.html) event before calling `PushNotification.init()`.
26
27**Note:** you will want to call `PushNotification.init()` each time your app starts. The remote push service can periodically reset your registration ID so this ensures you have the correct value.
28
29### Returns
30
31- Instance of `PushNotification`.
32
33### Parameters
34
35Parameter | Type | Default | Description
36--------- | ---- | ------- | -----------
37`options` | `Object` | `{}` | An object describing relevant specific options for all target platforms.
38
39All available option attributes are described bellow. Currently, there are no Windows specific options.
40
41#### Android
42
43Attribute | Type | Default | Description
44--------- | ---- | ------- | -----------
45`android.icon` | `string` | | Optional. The name of a drawable resource to use as the small-icon. The name should not include the extension.
46`android.iconColor` | `string` | | Optional. Sets the background color of the small icon on Android 5.0 and greater. [Supported Formats](http://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String))
47`android.sound` | `boolean` | `true` | Optional. If `true` it plays the sound specified in the push data or the default system sound.
48`android.vibrate` | `boolean` | `true` | Optional. If `true` the device vibrates on receipt of notification.
49`android.clearBadge` | `boolean` | `false` | Optional. If `true` the icon badge will be cleared on init and before push messages are processed.
50`android.clearNotifications` | `boolean` | `true` | Optional. If `true` the app clears all pending notifications when it is closed.
51`android.forceShow` | `boolean` | `false` | Optional. Controls the behavior of the notification when app is in foreground. If `true` and app is in foreground, it will show a notification in the notification drawer, the same way as when the app is in background (and `on('notification')` callback will be called *only when the user clicks the notification*). When `false` and app is in foreground, the `on('notification')` callback will be called immediately.
52`android.topics` | `array` | `[]` | Optional. If the array contains one or more strings each string will be used to subscribe to a FcmPubSub topic.
53`android.messageKey` | `string` | `message` | Optional. The key to search for text of notification.
54`android.titleKey` | `string` | `'title'` | Optional. The key to search for title of notification.
55
56#### Browser
57
58Attribute | Type | Default | Description
59--------- | ---- | ------- | -----------
60`browser.pushServiceURL` | `string` | `http://push.api.phonegap.com/v1/push` | Optional. URL for the push server you want to use.
61`browser.applicationServerKey` | `string` | `` | Optional. Your GCM API key if you are using VAPID keys.
62
63#### iOS
64
65All iOS boolean options can also be specified as `string`
66
67Attribute | Type | Default | Description
68--------- | ---- | ------- | -----------
69`ios.alert` | `boolean` | `false` | Optional. If `true` the device shows an alert on receipt of notification. **Note:** the value you set this option to the first time you call the init method will be how the application always acts. Once this is set programmatically in the init method it can only be changed manually by the user in Settings>Notifications>`App Name`. This is normal iOS behaviour.
70`ios.badge` | `boolean` | `false` | Optional. If `true` the device sets the badge number on receipt of notification. **Note:** the value you set this option to the first time you call the init method will be how the application always acts. Once this is set programmatically in the init method it can only be changed manually by the user in Settings>Notifications>`App Name`. This is normal iOS behaviour.
71`ios.sound` | `boolean` | `false` | Optional. If `true` the device plays a sound on receipt of notification. **Note:** the value you set this option to the first time you call the init method will be how the application always acts. Once this is set programmatically in the init method it can only be changed manually by the user in Settings>Notifications>`App Name`. This is normal iOS behaviour.
72`ios.clearBadge` | `boolean` | `false` | Optional. If `true` the badge will be cleared on app startup.
73`ios.categories` | `Object` | `{}` | Optional. The data required in order to enabled Action Buttons for iOS. See [Action Buttons on iOS](https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#action-buttons-1) for more details.
74
75#### iOS GCM support
76
77The following properties are used if you want use GCM on iOS.
78
79Attribute | Type | Default | Description
80--------- | ---- | ------- | -----------
81`ios.fcmSandbox` | `boolean` | `false` | Whether to use prod or sandbox GCM setting. Defaults to false.
82options
83`ios.topics` | `array` | `[]` | Optional. If the array contains one or more strings each string will be used to subscribe to a FcmPubSub topic.
84
85##### How GCM on iOS works.
86
87First it is kind of a misnomer as GCM does not send push messages directly to devices running iOS.
88
89What happens is on the device side is that it registers with APNS, then that registration ID is sent to GCM which returns a different GCM specific ID. That is the ID you get from the push plugin `registration` event.
90
91When you send a message to GCM using that ID, what it does is look up the APNS registration ID on it's side and forward the message you sent to GCM on to APSN to deliver to your iOS device.
92
93Make sure that the certificate you build with matches your `fcmSandbox` value.
94
95- If you build your app as development and set `fcmSandbox: false` it will fail.
96- If you build your app as production and set `fcmSandbox: true` it will fail.
97- If you build your app as development and set `fcmSandbox: true` but haven't uploaded the development certs to Google it will fail.
98- If you build your app as production and set `fcmSandbox: false` but haven't uploaded the production certs to Google it will fail.
99
100> Note: The integration between GCM and APNS is a bit finicky. Personally, I feel it is much better to send pushes to Android using GCM and pushes to iOS using APNS which this plugin does support.
101
102### Example
103
104```javascript
105const push = PushNotification.init({
106 android: {
107 },
108 browser: {
109 pushServiceURL: 'http://push.api.phonegap.com/v1/push'
110 },
111 ios: {
112 alert: "true",
113 badge: true,
114 sound: 'false'
115 },
116 windows: {}
117});
118```
119
120## PushNotification.hasPermission(successHandler)
121
122Checks whether the push notification permission has been granted.
123
124### Parameters
125
126Parameter | Type | Default | Description
127--------- | ---- | ------- | -----------
128`successHandler` | `Function` | | Is called when the api successfully retrieves the details on the permission.
129
130### Callback parameters
131
132#### `successHandler`
133
134Parameter | Type | Description
135--------- | ---- | -----------
136`data.isEnabled` | `Boolean` | Whether the permission for push notifications has been granted.
137
138### Example
139
140```javascript
141PushNotification.hasPermission((data) => {
142 if (data.isEnabled) {
143 console.log('isEnabled');
144 }
145});
146```
147
148## PushNotification.createChannel(successHandler, failureHandler, channel)
149
150Create a new notification channel for Android O and above.
151
152### Parameters
153
154Parameter | Type | Default | Description
155--------- | ---- | ------- | -----------
156`successHandler` | `Function` | | Is called when the api successfully creates a channel.
157`failureHandler` | `Function` | | Is called when the api fails to create a channel.
158`channel` | `Object` | | The options for the channel.
159
160### Example
161
162```javascript
163PushNotification.createChannel(() => {
164 console.log('success');
165}, () => {
166 console.log('error');
167}, {
168 id: "testchannel1",
169 description: "My first test channel",
170 importance: 3
171});
172```
173
174The above will create a channel for your app. You'll need to provide the `id`, `description` and `importance` properties. The importance property goes from 1 = Lowest, 2 = Low, 3 = Normal, 4 = High and 5 = Highest.
175
176## PushNotification.deleteChannel(successHandler, failureHandler, channelId)
177
178Delete a notification channel for Android O and above.
179
180### Parameters
181
182Parameter | Type | Default | Description
183--------- | ---- | ------- | -----------
184`successHandler` | `Function` | | Is called when the api successfully creates a channel.
185`failureHandler` | `Function` | | Is called when the api fails to create a channel.
186`channelId` | `String` | | The ID of the channel.
187
188### Example
189
190```javascript
191PushNotification.deleteChannel(() => {
192 console.log('success');
193}, () => {
194 console.log('error');
195}, 'testchannel1');
196```
197
198## PushNotification.listChannels(successHandler)
199
200Returns a list of currently configured channels.
201
202### Parameters
203
204Parameter | Type | Default | Description
205--------- | ---- | ------- | -----------
206`successHandler` | `Function` | | Is called when the api successfully retrieves the list of channels.
207
208### Callback parameters
209
210#### `successHandler`
211
212Parameter | Type | Description
213--------- | ---- | -----------
214`channels` | `JSONArrary` | List of channel objects.
215
216### Example
217
218```javascript
219PushNotification.listChannels((channels) => {
220 for(let channel of channels) {
221 console.log(`ID: ${channel.id} Description: ${channel.description}`);
222 }
223});
224```
225
226## push.on(event, callback)
227
228### Parameters
229
230Parameter | Type | Default | Description
231--------- | ---- | ------- | -----------
232`event` | `string` | | Name of the event to listen to. See below for all the event names.
233`callback` | `Function` | | Is called when the event is triggered.
234
235## push.on('registration', callback)
236
237The event `registration` will be triggered on each successful registration with the 3rd party push service.
238
239### Callback parameters
240
241Parameter | Type | Description
242--------- | ---- | -----------
243`data.registrationId` | `string` | The registration ID provided by the 3rd party remote push service.
244`data.registrationType` | `string` | The registration type of the 3rd party remote push service. Either FCM or APNS.
245
246### Example
247
248```javascript
249push.on('registration', (data) => {
250 console.log(data.registrationId);
251 console.log(data.registrationType);
252});
253```
254
255For APNS users: the `registrationId` you will get will be a production or sandbox id according to how the app was built. ([Source](https://developer.apple.com/library/ios/technotes/tn2265/_index.html))
256
257> Note: There is a separate persistent connection to the push service for each environment. The operating system establishes a persistent connection to the sandbox environment for development builds; ad hoc and distribution builds connect to the production environment.
258
259
260
261### Common Problems
262
263#### Got JSON Exception TIMEOUT
264
265If you run this plugin on older versions of Android and you get an error:
266
267```
268E/PushPlugin(20077): execute: Got JSON Exception TIMEOUT
269```
270
271It means you are running an older version of Google Play Services. You will need to open the Google Play Store app and update your version of Google Play Services.
272
273## push.on('notification', callback)
274
275The event `notification` will be triggered each time a push notification is received by a 3rd party push service on the device.
276
277### Callback parameters
278
279Parameter | Type | Description
280--------- | ---- | -----------
281`data.message` | `string` | The text of the push message sent from the 3rd party service.
282`data.title` | `string` | The optional title of the push message sent from the 3rd party service.
283`data.count` | `string` | The number of messages to be displayed in the badge in iOS/Android or message count in the notification shade in Android. For windows, it represents the value in the badge notification which could be a number or a status glyph.
284`data.sound` | `string` | The name of the sound file to be played upon receipt of the notification.
285`data.image` | `string` | The path of the image file to be displayed in the notification.
286`data.launchArgs` | `string` | The args to be passed to the application on launch from push notification. This works when notification is received in background. (Windows Only)
287`data.additionalData` | `Object` | An optional collection of data sent by the 3rd party push service that does not fit in the above properties.
288`data.additionalData.foreground` | `boolean` | Whether the notification was received while the app was in the foreground
289`data.additionalData.coldstart` | `boolean` | Will be `true` if the application is started by clicking on the push notification, `false` if the app is already started.
290`data.additionalData.dismissed` | `boolean` | Is set to `true` if the notification was dismissed by the user
291
292### Example
293
294```javascript
295push.on('notification', (data) => {
296 console.log(data.message);
297 console.log(data.title);
298 console.log(data.count);
299 console.log(data.sound);
300 console.log(data.image);
301 console.log(data.additionalData);
302});
303```
304
305## push.on('error', callback)
306
307The event `error` will trigger when an internal error occurs and the cache is aborted.
308
309### Callback parameters
310
311Parameter | Type | Description
312--------- | ---- | -----------
313`e` | `Error` | Standard JavaScript error object that describes the error.
314
315### Example
316
317```javascript
318push.on('error', (e) => {
319 console.log(e.message);
320});
321```
322
323## push.off(event, callback)
324
325Removes a previously registered callback for an event.
326
327### Parameters
328
329Parameter | Type | Default | Description
330--------- | ---- | ------- | -----------
331`event` | `string` | | Name of the event type. The possible event names are the same as for the `push.on` function.
332`callback` | `Function` | | The same callback used to register with `push.on`.
333
334### Example
335```javascript
336const callback = (data) => { /*...*/};
337
338//Adding handler for notification event
339push.on('notification', callback);
340
341//Removing handler for notification event
342push.off('notification', callback);
343```
344
345**WARNING**: As stated in the example, you will have to store your event handler if you are planning to remove it.
346
347## push.unregister(successHandler, errorHandler, topics)
348
349The unregister method is used when the application no longer wants to receive push notifications. Beware that this cleans up all event handlers previously registered, so you will need to re-register them if you want them to function again without an application reload.
350
351If you provide a list of topics as an optional parameter then the application will unsubscribe from these topics but continue to receive other push messages.
352
353### Parameters
354
355Parameter | Type | Default | Description
356--------- | ---- | ------- | -----------
357`successHandler` | `Function` | | Is called when the api successfully unregisters.
358`errorHandler` | `Function` | | Is called when the api encounters an error while unregistering.
359`topics` | `Array` | | A list of topics to unsubscribe from.
360
361### Example
362
363```javascript
364push.unregister(() => {
365 console.log('success');
366}, () => {
367 console.log('error');
368});
369```
370
371## push.subscribe(topic, successHandler, errorHandler)
372
373The subscribe method is used when the application wants to subscribe a new topic to receive push notifications.
374
375### Parameters
376
377Parameter | Type | Default | Description
378--------- | ---- | ------- | -----------
379`topic` | `String` | | Topic to subscribe to.
380`successHandler` | `Function` | | Is called when the api successfully subscribes.
381`errorHandler` | `Function` | | Is called when the api encounters an error while subscribing.
382
383### Example
384
385```javascript
386push.subscribe('my-topic', () => {
387 console.log('success');
388}, (e) => {
389 console.log('error:', e);
390});
391```
392## push.unsubscribe(topic, successHandler, errorHandler)
393
394The unsubscribe method is used when the application no longer wants to receive push notifications from a specific topic but continue to receive other push messages.
395
396### Parameters
397
398Parameter | Type | Default | Description
399--------- | ---- | ------- | -----------
400`topic` | `String` | | Topic to unsubscribe from.
401`successHandler` | `Function` | | Is called when the api successfully unsubscribe.
402`errorHandler` | `Function` | | Is called when the api encounters an error while unsubscribing.
403
404### Example
405
406```javascript
407push.unsubscribe('my-topic', () => {
408 console.log('success');
409}, (e) => {
410 console.log('error:', e);
411});
412```
413
414## push.setApplicationIconBadgeNumber(successHandler, errorHandler, count) - iOS & Android only
415
416Set the badge count visible when the app is not running
417
418> Note: badges are not supported on all Android devices. See [our payload documentation](PAYLOAD.md#badges) for more details.
419
420### Parameters
421
422Parameter | Type | Default | Description
423--------- | ---- | ------- | -----------
424`successHandler` | `Function` | | Is called when the api successfully sets the icon badge number.
425`errorHandler` | `Function` | | Is called when the api encounters an error while trying to set the icon badge number.
426`count` | `number` | | Indicates what number should show up in the badge. Passing 0 will clear the badge. Each `notification` event contains a `data.count` value which can be used to set the badge to correct number.
427
428### Example
429
430```javascript
431push.setApplicationIconBadgeNumber(() => {
432 console.log('success');
433}, () => {
434 console.log('error');
435}, 2);
436```
437
438## push.getApplicationIconBadgeNumber(successHandler, errorHandler) - iOS & Android only
439
440Get the current badge count visible when the app is not running
441
442### Parameters
443
444Parameter | Type | Default | Description
445--------- | ---- | ------- | -----------
446`successHandler` | `Function` | | Is called when the api successfully retrieves the icon badge number.
447`errorHandler` | `Function` | | Is called when the api encounters an error while trying to retrieve the icon badge number.
448
449### Callback parameters
450
451#### `successHandler`
452
453Parameter | Type | Description
454--------- | ---- | -----------
455`n` | `number` | An integer which is the current badge count.
456
457### Example
458
459```javascript
460push.getApplicationIconBadgeNumber((n) => {
461 console.log('success', n);
462}, () => {
463 console.log('error');
464});
465```
466
467## push.finish(successHandler, errorHandler, id) - iOS only
468
469Tells the OS that you are done processing a background push notification.
470
471### Parameters
472
473Parameter | Type | Default | Description
474--------- | ---- | ------- | -----------
475`successHandler` | `Function` | | Is called when the api successfully completes background push processing.
476`errorHandler` | `Function` | | Is called when the api encounters an error while processing and completing the background push.
477`id` | `String` | | Tells the OS which background process is complete.
478
479### Example
480
481```javascript
482push.finish(() => {
483 console.log('success');
484}, () => {
485 console.log('error');
486}, 'push-1');
487```
488
489## push.clearAllNotifications(successHandler, errorHandler) - iOS & Android only
490
491Tells the OS to clear all notifications from the Notification Center
492
493### Parameters
494
495Parameter | Type | Default | Description
496--------- | ---- | ------- | -----------
497`successHandler` | `Function` | | Is called when the api successfully clears the notifications.
498`errorHandler` | `Function` | | Is called when the api encounters an error when attempting to clears the notifications.
499
500### Example
501
502```javascript
503push.clearAllNotifications(() => {
504 console.log('success');
505}, () => {
506 console.log('error');
507});
508```