Socket
Socket
Sign inDemoInstall

nativescript-push-notifications

Package Overview
Dependencies
Maintainers
2
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nativescript-push-notifications - npm Package Compare versions

Comparing version 0.1.5 to 0.2.0

index.d.ts

31

package.json
{
"name": "nativescript-push-notifications",
"version": "0.1.5",
"version": "0.2.0",
"description": "Receive push notifications in your NativeScript app on Android and iOS.",
"main": "push-plugin",
"author": {
"name": "NativeScript Team"
"typings": "index.d.ts",
"author": "NativeScript Team",
"bugs": {
"url": "https://github.com/NativeScript/push-plugin/issues"
},

@@ -13,2 +16,4 @@ "repository": {

"license": "Apache-2.0",
"homepage": "https://github.com/NativeScript/push-plugin",
"readmeFilename": "README.md",
"nativescript": {

@@ -28,9 +33,21 @@ "platforms": {

"scripts": {
"postinstall": "node postinstall.js",
"preuninstall": "node preuninstall.js"
"tsc": "tsc -skipLibCheck",
"build": "npm i --ignore-scripts && tsc && cd ../publish && ./pack.sh",
"tslint": "cd .. && tslint \"**/*.ts\" --config tslint.json --exclude \"**/node_modules/**\"",
"plugin.link": "npm link && cd ../demo && npm link nativescript-push-notifications && cd ../src",
"clean": "cd ../demo && rimraf hooks node_modules platforms && cd ../src && rimraf node_modules && npm run plugin.link",
"ci.tslint": "npm i --ignore-scripts && tslint '**/*.ts' --config ../tslint.json --exclude '**/node_modules/**'",
"postinstall": "node scripts/postinstall.js",
"preuninstall": "node scripts/preuninstall.js"
},
"dependencies": {
"nativescript-hook": "0.2.1"
"nativescript-hook": "0.2.2"
},
"typings": "./definitions.d.ts"
"devDependencies": {
"rimraf": "^2.6.2",
"tns-core-modules": "^3.3.0",
"tns-platform-declarations": "^3.3.0",
"tslint": "^5.8.0",
"typescript": "^2.6.1"
}
}

@@ -1,54 +0,46 @@

module.exports = (function () {
var app = require('application');
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var app = require("tns-core-modules/application");
(function () {
var registerLifecycleEvents = function () {
com.telerik.pushplugin.PushLifecycleCallbacks.registerCallbacks(app.android.nativeApp);
};
// Hook on the application events
if (app.android.nativeApp) {
registerLifecycleEvents();
} else {
}
else {
app.on(app.launchEvent, registerLifecycleEvents);
}
var pluginObject = {
register: function (options, successCallback, errorCallback) {
com.telerik.pushplugin.PushPlugin.register(app.android.context, options.senderID,
new com.telerik.pushplugin.PushPluginListener(
{
success: successCallback,
error: errorCallback
})
);
},
unregister: function (onSuccessCallback, onErrorCallback, options) {
com.telerik.pushplugin.PushPlugin.unregister(app.android.context, options.senderID, new com.telerik.pushplugin.PushPluginListener(
{
success: onSuccessCallback,
error: onErrorCallback
}
));
},
onMessageReceived: function (callback) {
com.telerik.pushplugin.PushPlugin.setOnMessageReceivedCallback(
new com.telerik.pushplugin.PushPluginListener(
{
success: callback
})
);
},
onTokenRefresh : function (callback) {
com.telerik.pushplugin.PushPlugin.setOnTokenRefreshCallback(
new com.telerik.pushplugin.PushPluginListener(
{
success: callback
})
);
},
areNotificationsEnabled : function (callback) {
var bool = com.telerik.pushplugin.PushPlugin.areNotificationsEnabled();
callback(bool);
}
};
return pluginObject;
})();
function register(options, successCallback, errorCallback) {
com.telerik.pushplugin.PushPlugin.register(app.android.context, options.senderID, new com.telerik.pushplugin.PushPluginListener({
success: successCallback,
error: errorCallback
}));
}
exports.register = register;
function unregister(onSuccessCallback, onErrorCallback, options) {
com.telerik.pushplugin.PushPlugin.unregister(app.android.context, options.senderID, new com.telerik.pushplugin.PushPluginListener({
success: onSuccessCallback,
error: onErrorCallback
}));
}
exports.unregister = unregister;
function onMessageReceived(onSuccessCallback) {
com.telerik.pushplugin.PushPlugin.setOnMessageReceivedCallback(new com.telerik.pushplugin.PushPluginListener({
success: onSuccessCallback
}));
}
exports.onMessageReceived = onMessageReceived;
function onTokenRefresh(onSuccessCallback) {
com.telerik.pushplugin.PushPlugin.setOnTokenRefreshCallback(new com.telerik.pushplugin.PushPluginListener({
success: onSuccessCallback
}));
}
exports.onTokenRefresh = onTokenRefresh;
function areNotificationsEnabled(onSuccessCallback) {
var bool = com.telerik.pushplugin.PushPlugin.areNotificationsEnabled();
onSuccessCallback(bool);
}
exports.areNotificationsEnabled = areNotificationsEnabled;
//# sourceMappingURL=push-plugin.android.js.map

@@ -1,170 +0,139 @@

module.exports = (function() {
var iosApp = require('application').ios;
var pushHandler;
var pushManager
(function() {
if (!pushHandler) {
pushHandler = Push.alloc().init();
pushManager = PushManager.alloc().init();
}
})();
var pushPluginObject = {
_init: function(settings) {
if (!!this.isInitialized) return;
var self = this;
// initialize the native push plugin
this.settings = settings;
this.notificationCallbackIOS = settings.notificationCallbackIOS;
// subscribe to the notification received event.
this._addObserver("notificationReceived", function(context) {
var userInfo = JSON.parse(context.userInfo.objectForKey('message'));
self.notificationCallbackIOS(userInfo);
});
this.isInitialized = true;
},
register: function(settings, success, error) {
this._init(settings);
var self = this;
if (!this.didRegisterObserver) { // make sure that the events are not attached more than once
this.didRegisterObserver = this._addObserver("didRegisterForRemoteNotificationsWithDeviceToken", function(result) {
self._removeObserver(self.didRegisterObserver, "didRegisterForRemoteNotificationsWithDeviceToken");
self.didRegisterObserver = undefined;
var token = result.userInfo.objectForKey('message');
success(token);
});
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var app = require("tns-core-modules/application");
var iosApp = app.ios;
var pushHandler;
var pushManager;
var pushSettings;
(function () {
if (!pushSettings) {
pushSettings = {};
}
if (!pushHandler) {
pushHandler = Push.alloc().init();
}
if (!pushManager) {
pushManager = PushManager.alloc().init();
}
})();
var _init = function (settings) {
if (!!pushSettings.isInitialized)
return;
pushSettings.settings = settings;
pushSettings.notificationCallbackIOS = settings.notificationCallbackIOS;
_addObserver("notificationReceived", function (context) {
var userInfo = JSON.parse(context.userInfo.objectForKey('message'));
pushSettings.notificationCallbackIOS(userInfo);
});
pushSettings.isInitialized = true;
};
var _mapCategories = function (interactiveSettings) {
var categories = [];
for (var i = 0; i < interactiveSettings.categories.length; i++) {
var currentCategory = interactiveSettings.categories[i];
var mappedCategory = {
identifier: currentCategory.identifier,
actionsForDefaultContext: [],
actionsForMinimalContext: []
};
for (var j = 0; j < interactiveSettings.actions.length; j++) {
var currentAction = interactiveSettings.actions[j];
if (currentCategory.actionsForMinimalContext.indexOf(currentAction.identifier) > -1) {
mappedCategory.actionsForMinimalContext.push(currentAction);
}
if (!this.didFailToRegisterObserver) {
this.didFailToRegisterObserver = this._addObserver("didFailToRegisterForRemoteNotificationsWithError", function(e) {
self._removeObserver(self.didFailToRegisterObserver, "didFailToRegisterForRemoteNotificationsWithError");
self.didFailToRegisterObserver = undefined;
error(e);
});
if (currentCategory.actionsForDefaultContext.indexOf(currentAction.identifier) > -1) {
mappedCategory.actionsForDefaultContext.push(currentAction);
}
pushHandler.register(self.settings);
},
registerUserNotificationSettings: function(success,error) {
var self = this;
if (self.settings && self.settings.interactiveSettings) {
var interactiveSettings = self.settings.interactiveSettings;
var notificationTypes = [];
if (self.settings.alert) {
notificationTypes.push("alert");
}
if (self.settings.badge) {
notificationTypes.push("badge");
}
if (self.settings.sound) {
notificationTypes.push("sound");
}
if (!this.registerUserSettingsObserver) {
this.registerUserSettingsObserver = this._addObserver("didRegisterUserNotificationSettings", function() {
self._removeObserver(self.registerUserSettingsObserver, "didRegisterUserNotificationSettings");
self.registerUserSettingsObserver = undefined;
success();
});
}
if (!this.failToRegisterUserSettingsObserver) {
this.failToRegisterUserSettingsObserver = this._addObserver("failToRegisterUserNotificationSettings", function(error) {
self._removeObserver(self.didFailToRegisterObserver, "failToRegisterUserNotificationSettings");
self.failToRegisterUserSettingsObserver = undefined;
error(error);
});
}
pushHandler.registerUserNotificationSettings({
types: notificationTypes,
categories: self._mapCategories(interactiveSettings)
});
} else {
}
categories.push(mappedCategory);
}
return categories;
};
var _addObserver = function (eventName, callback) {
return iosApp.addNotificationObserver(eventName, callback);
};
var _removeObserver = function (observer, eventName) {
iosApp.removeNotificationObserver(observer, eventName);
};
function register(settings, success, error) {
_init(settings);
if (!pushSettings.didRegisterObserver) {
pushSettings.didRegisterObserver = _addObserver("didRegisterForRemoteNotificationsWithDeviceToken", function (result) {
_removeObserver(pushSettings.didRegisterObserver, "didRegisterForRemoteNotificationsWithDeviceToken");
pushSettings.didRegisterObserver = undefined;
var token = result.userInfo.objectForKey('message');
success(token);
});
}
if (!pushSettings.didFailToRegisterObserver) {
pushSettings.didFailToRegisterObserver = _addObserver("didFailToRegisterForRemoteNotificationsWithError", function (e) {
_removeObserver(pushSettings.didFailToRegisterObserver, "didFailToRegisterForRemoteNotificationsWithError");
pushSettings.didFailToRegisterObserver = undefined;
error(e);
});
}
pushHandler.register(pushSettings.settings);
}
exports.register = register;
function registerUserNotificationSettings(success, error) {
if (pushSettings.settings && pushSettings.settings.interactiveSettings) {
var interactiveSettings = pushSettings.settings.interactiveSettings;
var notificationTypes = [];
if (pushSettings.settings.alert) {
notificationTypes.push("alert");
}
if (pushSettings.settings.badge) {
notificationTypes.push("badge");
}
if (pushSettings.settings.sound) {
notificationTypes.push("sound");
}
if (!pushSettings.registerUserSettingsObserver) {
pushSettings.registerUserSettingsObserver = _addObserver("didRegisterUserNotificationSettings", function () {
_removeObserver(pushSettings.registerUserSettingsObserver, "didRegisterUserNotificationSettings");
pushSettings.registerUserSettingsObserver = undefined;
success();
}
},
unregister: function(done) {
var self = this;
if (!this.didUnregisterObserver) {
this.didUnregisterObserver = this._addObserver("didUnregister", function(context) {
self._removeObserver(self.didUnregisterObserver, "didUnregister");
self.didUnregisterObserver = undefined;
done(context);
});
}
pushHandler.unregister();
},
areNotificationsEnabled: function(done) {
var self = this;
if (!this.areNotificationsEnabledObserver) {
this.areNotificationsEnabledObserver = this._addObserver("areNotificationsEnabled", function(result) {
var areEnabledStr = result.userInfo.objectForKey('message');
var areEnabled;
if(areEnabledStr === "true"){
areEnabled = true;
}
self._removeObserver(self.areNotificationsEnabledObserver, "areNotificationsEnabled");
self.areNotificationsEnabledObserver = undefined;
done(areEnabled);
});
}
pushHandler.areNotificationsEnabled();
},
_mapCategories: function(interactiveSettings) {
var categories = [];
for (var i = 0; i < interactiveSettings.categories.length; i++) {
var currentCategory = interactiveSettings.categories[i];
var mappedCategory = {
identifier: currentCategory.identifier,
actionsForDefaultContext: [],
actionsForMinimalContext: []
}
for (var j = 0; j < interactiveSettings.actions.length; j++) {
var currentAction = interactiveSettings.actions[j];
if (currentCategory.actionsForMinimalContext.indexOf(currentAction.identifier) > -1) {
mappedCategory.actionsForMinimalContext.push(currentAction);
}
if (currentCategory.actionsForDefaultContext.indexOf(currentAction.identifier) > -1) {
mappedCategory.actionsForDefaultContext.push(currentAction);
}
}
categories.push(mappedCategory);
}
return categories;
},
_addObserver: function(eventName, callback) {
return iosApp.addNotificationObserver(eventName, callback);
},
_removeObserver: function(observer, eventName) {
iosApp.removeNotificationObserver(observer, eventName);
});
}
};
return pushPluginObject;
})();
if (!pushSettings.failToRegisterUserSettingsObserver) {
pushSettings.failToRegisterUserSettingsObserver = _addObserver("failToRegisterUserNotificationSettings", function (e) {
_removeObserver(pushSettings.didFailToRegisterObserver, "failToRegisterUserNotificationSettings");
pushSettings.failToRegisterUserSettingsObserver = undefined;
error(e);
});
}
pushHandler.registerUserNotificationSettings({
types: notificationTypes,
categories: _mapCategories(interactiveSettings)
});
}
else {
success();
}
}
exports.registerUserNotificationSettings = registerUserNotificationSettings;
function unregister(done) {
if (!pushSettings.didUnregisterObserver) {
pushSettings.didUnregisterObserver = _addObserver("didUnregister", function (context) {
_removeObserver(pushSettings.didUnregisterObserver, "didUnregister");
pushSettings.didUnregisterObserver = undefined;
done(context);
});
}
pushHandler.unregister();
}
exports.unregister = unregister;
function areNotificationsEnabled(done) {
if (!pushSettings.areNotificationsEnabledObserver) {
pushSettings.areNotificationsEnabledObserver = _addObserver("areNotificationsEnabled", function (result) {
var areEnabledStr = result.userInfo.objectForKey('message');
var areEnabled = areEnabledStr === "true";
_removeObserver(pushSettings.areNotificationsEnabledObserver, "areNotificationsEnabled");
pushSettings.areNotificationsEnabledObserver = undefined;
done(areEnabled);
});
}
pushHandler.areNotificationsEnabled();
}
exports.areNotificationsEnabled = areNotificationsEnabled;
//# sourceMappingURL=push-plugin.ios.js.map

@@ -5,6 +5,7 @@ # Push Plugin for NativeScript

- [Getting started](#getting-started)
- [API Reference](#api)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
- [API Reference](#api-reference)
- [Troubleshooting](#troubleshooting)
- [Using with Telerik Backend Services](#using-with-telerik-backend-services)
- [Android Configuration for using Firebase Cloud Messaging](#android-configuration-for-using-firebase-cloud-messaging)

@@ -14,14 +15,9 @@

## Getting started
## Installation
In the Command prompt / Terminal navigate to your application root folder and run:
- Create a new NativeScript application
tns plugin add nativescript-push-notifications
tns create MyApp
or use an existing one.
- Add the Push Plugin (from NPM). This will install the push plugin in the `node_modules` folder, in the root of the project. When adding a new platform (or using an existing one) the plugin will be added there as well. Go to the application folder and add the push plugin:
tns plugin add nativescript-push-notifications
## Configuration
### Android

@@ -35,35 +31,19 @@

- Add sample code in app/main-view-model.js in the function HelloWorldModel() like this one to subscribe and receive messages (enter your Firebase Cloud Messaging **Sender ID** in the options of the register method):
- Add the `google-settings.json` file with the FCM configuration to the `app/App_Resources/Android folder` in your app. If this file is not added, building the app for android will fail.
```javascript
var pushPlugin = require("nativescript-push-notifications");
var self = this;
pushPlugin.register({ senderID: '<ENTER_YOUR_PROJECT_NUMBER>' }, function (data){
self.set("message", "" + JSON.stringify(data));
}, function() { });
The plugin will default to version 11.4.2 of the `firebase-messaging` SDK. If you need to change the version, you can add a project ext property `firebaseMessagingVersion` like so:
pushPlugin.onMessageReceived(function callback(data) {
self.set("message", "" + JSON.stringify(data));
});
```
- Attach your phone to the PC, ensure "adb devices" command lists it and run the app on the phone:
tns run android
- The access token is written in the console and in the message area, after subscribing (Look for ObtainTokenThread log record). When sending a notification, the message below the TAP button should be changed with the message received.
The plugin will default to version 10.0.1 of the `firebase-messaging` SDK. If you need to change the version, you can add a project ext property `firebaseMessagingVersion` like so:
```
```Groovy
// in the root level of /app/App_Resources/Android/app.gradle:
project.ext {
firebaseMessagingVersion = "+" // OR the version you wish
}
```
```
### iOS
- Edit the package.json file in the root of application, by changing the bundle identifier to match the one from your Push Certificate. For example:
"id": "com.telerik.PushNotificationApp"
```
"id": "org.NativeScript.PushNotificationApp"
```

@@ -74,135 +54,184 @@ - Go to the application folder and add the iOS platform to the application

- Add sample code in app/main-view-model.js in the function HelloWorldModel() like this one to subscribe and receive messages (Enter your google project id in the options of the register method):
```javascript
var pushPlugin = require("nativescript-push-notifications");
var self = this;
var iosSettings = {
badge: true,
sound: true,
alert: true,
interactiveSettings: {
actions: [{
identifier: 'READ_IDENTIFIER',
title: 'Read',
activationMode: "foreground",
destructive: false,
authenticationRequired: true
}, {
identifier: 'CANCEL_IDENTIFIER',
title: 'Cancel',
activationMode: "foreground",
destructive: true,
authenticationRequired: true
}],
categories: [{
identifier: 'READ_CATEGORY',
actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
}]
},
notificationCallbackIOS: function (data) {
self.set("message", "" + JSON.stringify(data));
}
};
## Usage
### Android
pushPlugin.register(iosSettings, function (data) {
self.set("message", "" + JSON.stringify(data));
Add code in your view model or compoent to subscribe and receive messages (don't forget to enter your Firebase Cloud Messaging **Sender ID** in the options of the register method):
// Register the interactive settings
if(iosSettings.interactiveSettings) {
pushPlugin.registerUserNotificationSettings(function() {
alert('Successfully registered for interactive push.');
}, function(err) {
alert('Error registering for interactive push: ' + JSON.stringify(err));
});
}
}, function() { });
*TypeScript*
```TypeScript
import * as pushPlugin from "nativescript-push-notifications";
pushPlugin.register({ senderID: '<ENTER_YOUR_PROJECT_NUMBER>' }, (token: String) => {
alert("Device registered. Access token: " + token);;
}, function() { });
pushPlugin.onMessageReceived((stringifiedData: String, fcmNotification: any) => {
const notificationBody = fcmNotification && fcmNotification.getBody();
alert("Message received!\n" + notificationBody + "\n" + stringifiedData);
});
```
- Run the code
*Javascript*
```Javascript
var pushPlugin = require("nativescript-push-notifications");
pushPlugin.register({ senderID: '<ENTER_YOUR_PROJECT_NUMBER>' }, function (data){
alert("message", "" + data);
}, function() { });
tns run ios
- Send notifications
## API
```javascript
// Get reference to the push plugin module.
var pushPlugin = require('nativescript-push-notifications');
pushPlugin.onMessageReceived(function callback(stringifiedData, fcmNotification) {
var notificationBody = fcmNotification && fcmNotification.getBody();
alert("Message received!\n" + notificationBody + "\n" + stringifiedData);
});
```
- ***register*** - use to subscribe device for push notifications
- Run the app on the phone or emulator:
> register(settings, successCallback, errorCallback)
tns run android
```javascript
- The access token is written in the console and displayed on the device after the plugin sucessfully subscribes to receive notifications. When a notification comes, the message will be displayed in the notification area if the app is closed or handled directly in the onMessageReceived callback if the app is open.
var settings = {
// Android settings
senderID: '<ENTER_YOUR_PROJECT_NUMBER>', // Android: Required setting with the sender/project number
notificationCallbackAndroid: function(message, pushNotificationObject) { // Android: Callback to invoke when a new push is received.
alert(JSON.stringify(message));
},
### iOS
// iOS settings
badge: true, // Enable setting badge through Push Notification
sound: true, // Enable playing a sound
alert: true, // Enable creating a alert
Add code in your view model or compoent to subscribe and receive messages:
// Callback to invoke, when a push is received on iOS
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
*TypeScript*
```TypeScript
import * as pushPlugin from "nativescript-push-notifications";
const iosSettings = {
badge: true,
sound: true,
alert: true,
interactiveSettings: {
actions: [{
identifier: 'READ_IDENTIFIER',
title: 'Read',
activationMode: "foreground",
destructive: false,
authenticationRequired: true
}, {
identifier: 'CANCEL_IDENTIFIER',
title: 'Cancel',
activationMode: "foreground",
destructive: true,
authenticationRequired: true
}],
categories: [{
identifier: 'READ_CATEGORY',
actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
}]
},
notificationCallbackIOS: (message: any) => {
alert("Message received!\n" + JSON.stringify(message));
}
};
pushPlugin.register(iosSettings, (token: String) => {
alert("Device registered. Access token: " + token);
pushPlugin.register(settings,
// Success callback
function(token) {
// if we're on android device we have the onMessageReceived function to subscribe
// for push notifications
if(pushPlugin.onMessageReceived) {
pushPlugin.onMessageReceived(settings.notificationCallbackAndroid);
}
// Register the interactive settings
if(iosSettings.interactiveSettings) {
pushPlugin.registerUserNotificationSettings(() => {
alert('Successfully registered for interactive push.');
}, (err) => {
alert('Error registering for interactive push: ' + JSON.stringify(err));
});
}
}, (errorMessage: any) => {
alert("Device NOT registered! " + JSON.stringify(errorMessage));
});
```
alert('Device registered successfully');
*Javascript*
```Javascript
var pushPlugin = require("nativescript-push-notifications");
var iosSettings = {
badge: true,
sound: true,
alert: true,
interactiveSettings: {
actions: [{
identifier: 'READ_IDENTIFIER',
title: 'Read',
activationMode: "foreground",
destructive: false,
authenticationRequired: true
}, {
identifier: 'CANCEL_IDENTIFIER',
title: 'Cancel',
activationMode: "foreground",
destructive: true,
authenticationRequired: true
}],
categories: [{
identifier: 'READ_CATEGORY',
actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
}]
},
// Error Callback
function(error){
alert(error.message);
notificationCallbackIOS: function (data) {
alert("message", "" + JSON.stringify(data));
}
);
};
pushPlugin.register(iosSettings, function (data) {
alert("Device registered. Access token" + data);
// Register the interactive settings
if(iosSettings.interactiveSettings) {
pushPlugin.registerUserNotificationSettings(function() {
alert('Successfully registered for interactive push.');
}, function(err) {
alert('Error registering for interactive push: ' + JSON.stringify(err));
});
}
}, function() { });
```
- Run the app on the phone or simulator:
- ***unregister*** - use to unsubscribe from Push Notifications
tns run ios
> unregister(successCallback, errorCallback, settings)
## API Reference
```javascript
#### register(options, successCallback, errorCallback) - subscribe the device with Apple/Google push notifications services so the app can receive notifications. Options can contain:
pushPlugin.unregister(
// Success callback
function(){
alert('Device unregistered successfully');
},
// Error Callback
function(error){
alert(error.message);
},
| Option | Platform | Type | Description |
| --- | --- | --- | --- |
| senderID | Android | String | The Sender ID for the FCM project. This option is required for Android. |
| badge | iOS | Boolean | Enable setting the badge through Push Notification. |
| sound | iOS | Boolean | Enable playing a sound. |
| alert | iOS | Boolean | Enable creating a alert. |
| clearBadge | iOS | Boolean | Enable clearing the badge on push registration. |
| notificationCallbackIOS | iOS | Function | Callback to invoke, when a push is received on iOS. |
| interactiveSettings | iOS | Object | Interactive settings for use when registerUserNotificationSettings is used on iOS. |
// The settings from the registration phase
settings
);
The interactiveSettings object for iOS can contain the following:
```
| Option | Type | Description |
| --- | --- | --- |
| actions | Array | A list of iOS interactive notification actions. |
| categories | Array | A list of iOS interactive notification categories. |
- **Register for interactive push notifications (iOS >= 8.0)** - in order to handle interacitve notifications, you have to pass additional settings while registering your device. The message object in the **notificationCallbackIOS** will contain a property with the value of the identifier.
The `actions` array from the iOS interactive settings contains:
> register(settings, successCallback, errorCallback)
| Option | Type | Description |
| --- | --- | --- |
| identifier | String | Required. String identifier of the action. |
| title | String | Required. Title of the button action. |
| activationMode | String | Set to either "foreground" or "background" to launch the app in foreground/background and respond to the action. |
| destructive | Boolean | Enable if the action is destructive. Will change the action color to red instead of the default. |
| authenticationRequired | Boolean | Enable if the device must be unlocked to perform the action. |
| behavior | String | Set if the action has a different behavior - e.g. text input. |
```javascript
The `categories` array from the iOS interactive settings contains:
| Option | Type | Description |
| --- | --- | --- |
| identifier | String | Required. String identifier of the category. |
| actionsForDefaultContext | Array | Required. Array of string identifiers of actions. |
| actionsForMinimalContext | Array | Required. Array of string identifiers of actions. |
*Javascript*
```Javascript
var settings = {

@@ -264,26 +293,89 @@ badge: true,

- ***areNotificationsEnabled*** - check if the notifications for the device are enabled. Returns true/false. Applicable only for iOS, for Android always returns true.
#### unregister(successCallback, errorCallback, options) - unsubscribe the device so the app stops receiving push notifications. The options object is the same as on the `register` method.
> areNotificationsEnabled(callback)
| Parameter | Platform | Type | Description |
| --- | --- | --- | --- |
| successCallback | iOS | Function | Called when app is successfully unsubscribed. Has one object parameter with the result. |
| successCallback | Android | Function | Called when app is successfully unsubscribed. Has one string parameter with the result. |
| errorCallback | Android | Function | Called when app is NOT successfully unsubscribed. Has one parameter containing the error. |
| options | Android | Function | Called when app is NOT successfully unsubscribed. Has one parameter containing the error. |
```javascript
*Javascript*
```Javascript
pushPlugin.unregister(
// Success callback
function(result) {
alert('Device unregistered successfully');
},
// Error Callback
function(errorMessage) {
alert(errorMessage);
},
// The settings from the registration phase
settings
);
```
#### areNotificationsEnabled(successCallback) - check if push notifications are enabled (iOS only, always returns true on Android)
| Parameter | Platform | Type | Description |
| --- | --- | --- | --- |
| successCallback | iOS/Android | Function | Called with one boolean parameter containing the result from the notifications enabled check. |
*Javascript*
```Javascript
pushPlugin.areNotificationsEnabled(function(areEnabled) {
alert('Are Notifications enabled: ' + areEnabled);
});
```
- ***onTokenRefresh*** - Android only, subscribe for the token refresh event (Used to obtain the new token in cases where google revoke the old one)
### Android only:
> onTokenRefresh(callback)
#### onMessageReceived(callback) - register a callback function to execute when receiving a notification. Callback function has the followint parameters:
```javascript
| Parameter | Type | Description |
| --- | --- | --- |
| stringifiedData | String | A string containing JSON data from the notification |
| fcmNotification | Object | iOS/Android | Function | The FCMNotification object. |
pushPlugin.onTokenRefresh(function(token){
The fcmNotification object contains the following methods:
| Method | Returns |
| --- | --- |
| getBody() | String |
| getBodyLocalizationArgs() | String[] |
| getBodyLocalizationKey() | String |
| getClickAction() | String |
| getColor() | String |
| getIcon() | String |
| getSound() | String |
| getTag() | String |
| getTitle() | String |
| getTitleLocalizationArgs() | String[] |
| getTitleLocalizationKey() | String |
#### onTokenRefresh(callback) - register a callback function to execute when the old token is revoked and a new token is obtained.
| Parameter | Type | Description |
| --- | --- | --- |
| callback | Function | Called with a single string parameter containing the FCM new token. |
*Javascript*
```Javascript
pushPlugin.onTokenRefresh(function(token) {
alert(token);
});
});
```
### iOS only:
#### registerUserNotificationSettings(successCallback, errorCallback) - used to register for interactive push on iOS.
| Parameter | Type | Description |
| --- | --- | --- |
| successCallback | Function | Called when app is successfully unsubscribed. Has one object parameter with the result. |
| errorCallback | Function | Called when app is NOT successfully unsubscribed. Has one parameter containing the error. |
## Troubleshooting

@@ -329,21 +421,12 @@

## Using with Telerik Backend Services
In order to use the plugin with Telerik Backend Services take a look at the official sample:
[Telerik Backend Services NativeScript Push Sample](https://github.com/NativeScript/sample-push-plugin)
## Android Configuration for using Firebase Cloud Messaging
From version **0.1.0** the `nativescript-push-notifications` module for Android relies on the Firebase Cloud Messaging (FCM) SDK. In the steps below you will be guided to complete a few additional steps to prepare your Android app to receive push notifications from FCM.
The `nativescript-push-notifications` module for Android relies on the Firebase Cloud Messaging (FCM) SDK. In the steps below you will be guided to complete a few additional steps to prepare your Android app to receive push notifications from FCM.
1. Add the FCM SDK
> Since version 0.1.1 thе `google-services` plugin is added via a hook. You can skip this step for versions 0.1.1 and above.
> Thе `google-services` plugin is added automatically. If this fails, you can try adding it manually:
- Navigate to the project `platforms/android/` folder and locate the application-level `build.gradle` file
- Add the `google-services` plugin to the list of other dependencies in your app's `build.gradle` file
- Navigate to the project `platforms/android/` folder and locate the application-level `build.gradle` file
- Add the `google-services` plugin to the list of other dependencies in your app's `build.gradle` file
```Groovy

@@ -356,5 +439,3 @@ dependencies {

```
- Add the following line be at the bottom of your `build.gradle` file to enable the Gradle plugin
- Add the following line be at the bottom of your `build.gradle` file to enable the Gradle plugin
```Groovy

@@ -364,3 +445,3 @@ apply plugin: 'com.google.gms.google-services'

1. Add the `google-services.json` file
2. Add the `google-services.json` file

@@ -371,8 +452,6 @@ To use FCM, you need this file. It contains configurations and credentials for your Firebase project. To obtain this follow the instructions for adding Firebase to your project from the official [documentation](https://firebase.google.com/docs/android/setup). Scroll down to the **Manually add Firebase** section.

1. Obtain the FCM Server Key
3. Obtain the FCM Server Key
This key is required to be able to send programmatically push notifications to your app. You can obtain this key from your Firebase project.
If you are using the Telerik Platform Notifications service refer to this [article](http://docs.telerik.com/platform/backend-services/javascript/push-notifications/push-enabling#android-settings) for instructions how to set up this key.
### Receive and Handle Messages from FCM on Android

@@ -382,3 +461,3 @@

The plugin extends the `FirebaseMessagingService` and overrides its `onMessageReceived` callback. In your app you need to use the `onMessageReceived(message, data, notification)` method of the NativeScript module.
The plugin extends the `FirebaseMessagingService` and overrides its `onMessageReceived` callback. In your app you need to use the `onMessageReceived(stringifiedData, fcmNotification)` method of the NativeScript module.

@@ -395,3 +474,3 @@ The behavior of the `onMessageReceived` callback in the module follows the behavior of the FCM service.

If the app is in foreground, it invokes the `onMessageReceived` callback with three arguments (message, data, notification).
If the app is in foreground, it invokes the `onMessageReceived` callback with two arguments (stringifiedData, fcmNotification).

@@ -404,3 +483,3 @@ If the app is in background, a notification is put in the tray. When tapped, it launches the app, but does not invoke the `onMessageReceived` callback.

- The app is in foreground, the `onMessageReceived` callback is invoked with parameters (message, data)
- The app is in foreground, the `onMessageReceived` callback is invoked with parameters (stringifiedData, fcmNotification)
- The app is in background, the `onMessageReceived` callback is not invoked. A notification is placed in the system tray. If the notification in the tray is tapped, the `data` part of the mixed message is available in the extras of the intent of the activity and are available in the respective [application event](https://docs.nativescript.org/core-concepts/application-lifecycle) of NativeScript.

@@ -410,3 +489,4 @@

```
*Javascript*
```Javascript
application.on(application.resumeEvent, function(args) {

@@ -429,14 +509,11 @@ if (args.android) {

Depending on the notification event and payload, the `onMessageReceived` callback is invoked with up to three arguments.
Depending on the notification event and payload, the `onMessageReceived` callback is invoked with two arguments.
* `message` - *String*. A string representation of the `data.message` value in the notification payload.
* `data` - *Object*. A JSON representation of the `data` value in the notification payload.
* `notification` - `RemoteMessage.Notification`. A representation of the `RemoteMessage.Notification` class which can be accessed according to its public methods. This parameter is available in case the callback was called from a message with a `notification` key in the payload.
* `stringifiedData` - *String*. A stringified JSON representation of the `data` value in the notification payload.
* `fcmNotification` - `RemoteMessage.Notification`. A representation of the `RemoteMessage.Notification` class which can be accessed according to its public methods. This parameter is available in case the callback was called from a message with a `notification` key in the payload.
#### Setting Notification Icon and Color
> From version 0.1.0 the module no longer adds as default a large icon of the notification because this was forcing developers to always use a large icon which is not the native behavior.
The plugin automatically handles some keys in the `data` object like `message`, `title`, `color`, `smallIcon`, `largeIcon` and uses them to construct a notification entry in the tray.
The plugin automatically handles some keys in the `data` object like `message`, `title`, `color`, `smallIcon`, `largeIcon` and uses them to construct a notification entry in the tray. More information on these keys is available in the documentation of the Telerik Platform Notifications service documentation [article](http://docs.telerik.com/platform/backend-services/javascript/push-notifications/send-and-target/push-send-target-examples).
Custom default color and icon for **notification** messages can be set in the `AndroidManifest.xml` inside the `application` directive:

@@ -443,0 +520,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc