New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

react-native-onesignal

Package Overview
Dependencies
Maintainers
12
Versions
137
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-onesignal - npm Package Compare versions

Comparing version 4.5.1 to 5.0.0-beta-01

.github/workflows/npm_deploy.yml

3

dist/events/EventManager.d.ts
import { EmitterSubscription, NativeModule } from 'react-native';
import { ChangeEvent } from '../models/Subscription';
export default class EventManager {

@@ -26,3 +25,3 @@ private RNOneSignal;

*/
addEventHandler<T>(eventName: string, handler: (event: ChangeEvent<T>) => void): void;
addEventHandler<T>(eventName: string, handler: (event: T) => void): void;
/**

@@ -29,0 +28,0 @@ * clears the event handler(s) for the event name

@@ -14,6 +14,4 @@ "use strict";

events_1.NOTIFICATION_WILL_SHOW,
events_1.NOTIFICATION_OPENED,
events_1.NOTIFICATION_CLICKED,
events_1.IN_APP_MESSAGE_CLICKED,
events_1.EMAIL_SUBSCRIPTION_CHANGED,
events_1.SMS_SUBSCRIPTION_CHANGED,
events_1.IN_APP_MESSAGE_WILL_DISPLAY,

@@ -28,3 +26,3 @@ events_1.IN_APP_MESSAGE_WILL_DISMISS,

this.oneSignalEventEmitter = new react_native_1.NativeEventEmitter(RNOneSignal);
this.eventHandlerMap = new Map(); // used for setters (single replacable callback)
this.eventHandlerMap = new Map(); // used for setters (single replaceable callback)
this.eventHandlerArrayMap = new Map(); // used for adders (multiple callbacks possible)

@@ -31,0 +29,0 @@ this.listeners = {};

export declare const NOTIFICATION_WILL_SHOW = "OneSignal-notificationWillShowInForeground";
export declare const NOTIFICATION_OPENED = "OneSignal-remoteNotificationOpened";
export declare const NOTIFICATION_CLICKED = "OneSignal-notificationClicked";
export declare const IN_APP_MESSAGE_CLICKED = "OneSignal-inAppMessageClicked";

@@ -10,3 +10,1 @@ export declare const IN_APP_MESSAGE_WILL_DISPLAY = "OneSignal-inAppMessageWillDisplay";

export declare const SUBSCRIPTION_CHANGED = "OneSignal-subscriptionChanged";
export declare const EMAIL_SUBSCRIPTION_CHANGED = "OneSignal-emailSubscriptionChanged";
export declare const SMS_SUBSCRIPTION_CHANGED = "OneSignal-smsSubscriptionChanged";
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SMS_SUBSCRIPTION_CHANGED = exports.EMAIL_SUBSCRIPTION_CHANGED = exports.SUBSCRIPTION_CHANGED = exports.PERMISSION_CHANGED = exports.IN_APP_MESSAGE_DID_DISMISS = exports.IN_APP_MESSAGE_WILL_DISMISS = exports.IN_APP_MESSAGE_DID_DISPLAY = exports.IN_APP_MESSAGE_WILL_DISPLAY = exports.IN_APP_MESSAGE_CLICKED = exports.NOTIFICATION_OPENED = exports.NOTIFICATION_WILL_SHOW = void 0;
// events
exports.SUBSCRIPTION_CHANGED = exports.PERMISSION_CHANGED = exports.IN_APP_MESSAGE_DID_DISMISS = exports.IN_APP_MESSAGE_WILL_DISMISS = exports.IN_APP_MESSAGE_DID_DISPLAY = exports.IN_APP_MESSAGE_WILL_DISPLAY = exports.IN_APP_MESSAGE_CLICKED = exports.NOTIFICATION_CLICKED = exports.NOTIFICATION_WILL_SHOW = void 0;
exports.NOTIFICATION_WILL_SHOW = 'OneSignal-notificationWillShowInForeground';
exports.NOTIFICATION_OPENED = 'OneSignal-remoteNotificationOpened';
exports.NOTIFICATION_CLICKED = 'OneSignal-notificationClicked';
exports.IN_APP_MESSAGE_CLICKED = 'OneSignal-inAppMessageClicked';
// In-App Message lifecycle events
exports.IN_APP_MESSAGE_WILL_DISPLAY = 'OneSignal-inAppMessageWillDisplay';

@@ -15,3 +13,1 @@ exports.IN_APP_MESSAGE_DID_DISPLAY = 'OneSignal-inAppMessageDidDisplay';

exports.SUBSCRIPTION_CHANGED = 'OneSignal-subscriptionChanged';
exports.EMAIL_SUBSCRIPTION_CHANGED = 'OneSignal-emailSubscriptionChanged';
exports.SMS_SUBSCRIPTION_CHANGED = 'OneSignal-smsSubscriptionChanged';

@@ -29,4 +29,2 @@ "use strict";

case events_1.SUBSCRIPTION_CHANGED:
case events_1.EMAIL_SUBSCRIPTION_CHANGED:
case events_1.SMS_SUBSCRIPTION_CHANGED:
return true;

@@ -33,0 +31,0 @@ default:

@@ -1,2 +0,2 @@

import { DeviceState, ChangeEvent, PermissionChange, SubscriptionChange, EmailSubscriptionChange, SMSSubscriptionChange } from './models/Subscription';
import { PushSubscription } from './models/Subscription';
import NotificationReceivedEvent from './events/NotificationReceivedEvent';

@@ -7,365 +7,223 @@ import { OpenedEvent } from './models/NotificationEvents';

export declare type LogLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export default class OneSignal {
export declare namespace OneSignal {
/** Initializes the OneSignal SDK. This should be called during startup of the application. */
function initialize(appId: string): void;
/**
* Completes OneSignal initialization by setting the OneSignal Application ID.
* @param {string} appId
* @returns void
* If your integration is user-centric, or you want the ability to identify the user beyond the current device, the
* login method should be called to identify the user.
*/
static setAppId(appId: string): void;
function login(externalId: string): void;
/**
* Add a callback that fires when the native push permission changes.
* @param {(event:ChangeEvent<PermissionChange>) => void} observer
* @returns void
* Once (or if) the user is no longer identifiable in your app (i.e. they logged out), the logout method should be
* called.
*/
static addPermissionObserver(observer: (event: ChangeEvent<PermissionChange>) => void): void;
function logout(): void;
/** True if the application requires user privacy consent, false otherwise. */
function getRequiresPrivacyConsent(): Promise<boolean>;
/** For GDPR users, your application should call this method before setting the App ID. */
function setRequiresPrivacyConsent(required: boolean): void;
/** Indicates whether privacy consent has been granted. */
function getPrivacyConsent(): Promise<boolean>;
/**
* Clears current permission observers.
* @returns void
* If your application is set to require the user's privacy consent, you can provide this consent using this method.
* Indicates whether privacy consent has been granted. This field is only relevant when the application has opted
* into data privacy protections.
*/
static clearPermissionObservers(): void;
function setPrivacyConsent(granted: boolean): void;
/** This method can be used to set if launch URLs should be opened in safari or within the application. */
function setLaunchURLsInApp(isEnabled: boolean): void;
/** Associates a temporary push token with an Activity ID on the OneSignal server. */
function enterLiveActivity(activityId: string, token: string, handler?: Function): void;
/**
* Add a callback that fires when the OneSignal subscription state changes.
* @param {(event:ChangeEvent<SubscriptionChange>) => void} observer
* @returns void
*/
static addSubscriptionObserver(observer: (event: ChangeEvent<SubscriptionChange>) => void): void;
/**
* Clears current subscription observers.
* @returns void
*/
static clearSubscriptionObservers(): void;
/**
* Add a callback that fires when the OneSignal email subscription changes.
* @param {(event:ChangeEvent<EmailSubscriptionChange>) => void} observer
* @returns void
*/
static addEmailSubscriptionObserver(observer: (event: ChangeEvent<EmailSubscriptionChange>) => void): void;
/**
* Clears current email subscription observers.
* @returns void
*/
static clearEmailSubscriptionObservers(): void;
/**
* Add a callback that fires when the OneSignal sms subscription changes.
* @param {(event:ChangeEvent<SMSSubscriptionChange>) => void} observer
* @returns void
*/
static addSMSSubscriptionObserver(observer: (event: ChangeEvent<SMSSubscriptionChange>) => void): void;
/**
* Clears current SMS subscription observers.
* @returns void
*/
static clearSMSSubscriptionObservers(): void;
/**
* Sets the handler that fires before the notification is displayed
* Callback parameter is a `NotificationReceivedEvent` with:
* - notification data
* - `complete` function that accepts the `NotificationReceivedEvent`
* @param {(event:NotificationReceivedEvent) => void} handler
*/
static setNotificationWillShowInForegroundHandler(handler: (event: NotificationReceivedEvent) => void): void;
/**
* Set the callback to run on notification open.
* @param {(openedEvent:OpenedEvent) => void} handler
* @returns void
*/
static setNotificationOpenedHandler(handler: (openedEvent: OpenedEvent) => void): void;
/**
* Prompts the user for push notifications permission in iOS and Android 13+.
* Use the fallbackToSettings parameter to prompt to open the settings app if a user has already declined push permissions.
*
* Call with promptForPushNotificationsWithUserResponse(fallbackToSettings?, handler?)
*
* Recommended: Do not use and instead follow: https://documentation.onesignal.com/docs/ios-push-opt-in-prompt.
* @param {boolean} fallbackToSettings
* @param {(response:boolean) => void} handler
* @returns void
*/
static promptForPushNotificationsWithUserResponse(fallbackToSettingsOrHandler?: boolean | ((response: boolean) => void), handler?: (response: boolean) => void): void;
/**
* Only applies to iOS (does nothing on Android as it always silently registers)
* Request for Direct-To-History push notification authorization
*
* For more information: https://documentation.onesignal.com/docs/ios-customizations#provisional-push-notifications
*
* @param {(response:boolean) => void} handler
* @returns void
*/
static registerForProvisionalAuthorization(handler: (response: boolean) => void): void;
/**
* Disable the push notification subscription to OneSignal.
* @param {boolean} disable
* @returns void
*/
static disablePush(disable: boolean): void;
/**
* Android Only. If notifications are disabled for your application, unsubscribe the user from OneSignal.
* @param {boolean} unsubscribe
* @returns void
*/
static unsubscribeWhenNotificationsAreDisabled(unsubscribe: boolean): void;
/**
* Associates a temporary push token with an Activity ID on the OneSignal server.
* @param {string} activityId
* @param {string} token
* @param {Function} handler
* @returns void
*/
static enterLiveActivity(activityId: string, token: string, handler?: Function): void;
/**
* Deletes activityId associated temporary push token on the OneSignal server.
* @param {string} activityId
* @param {Function} handler
* @returns void
*/
static exitLiveActivity(activityId: string, handler?: Function): void;
/**
* True if the application has location share activated, false otherwise
* @returns Promise<boolean>
*/
static isLocationShared(): Promise<boolean>;
/**
* Disable or enable location collection (defaults to enabled if your app has location permission).
* @param {boolean} shared
* @returns void
*/
static setLocationShared(shared: boolean): void;
/**
* Prompts the user for location permissions to allow geotagging from the OneSignal dashboard.
* @returns void
*/
static promptLocation(): void;
/**
* Gets the device state.
* This method returns a "snapshot" of the device state for when it was called.
* @returns Promise<DeviceState | null>
*/
static getDeviceState(): Promise<DeviceState | null>;
/**
* Allows you to set the app defined language with the OneSignal SDK.
* @param {string} language
* @param {(success:object) => void} onSuccess
* @param {(failure:object) => void} onFailure
* @returns void
*/
static setLanguage(language: string, onSuccess?: (success: object) => void, onFailure?: (failure: object) => void): void;
/**
* Tag a user based on an app event of your choosing so they can be targeted later via segments.
* @param {string} key
* @param {string} value
* @returns void
*/
static sendTag(key: string, value: string): void;
/**
* Tag a user with multiple tags based on an app event of your choosing so they can be targeted later via segments.
* @param {[key: string]: string} tags
* @returns void
*/
static sendTags(tags: {
[key: string]: string;
}): void;
/**
* Retrieve a list of tags that have been set on the user from the OneSignal server.
* @param {(tags: {[key: string]: string} | null) => void} handler
* @returns void
*/
static getTags(handler: (tags: {
[key: string]: string;
} | null) => void): void;
/**
* Deletes a single tag that was previously set on a user.
* @param {string} key
* @returns void
*/
static deleteTag(key: string): void;
/**
* Deletes multiple tags that were previously set on a user.
* @param {string[]} keys
*/
static deleteTags(keys: string[]): void;
/**
* Allows you to set the user's email address with the OneSignal SDK.
* @param {string} email
* @param {string} emailAuthCode
* @param {Function} handler
* @returns void
*/
static setEmail(email: string, emailAuthCode?: string | null, handler?: Function): void;
/**
* If your app implements logout functionality, you can call logoutEmail to dissociate the email from the device.
* @param {Function} handler
*/
static logoutEmail(handler?: Function): void;
/**
* Allows you to set the user's SMS number with the OneSignal SDK.
* @param {string} smsNumber
* @param {string} smsAuthCode
* @param {Function} handler
* @returns void
*/
static setSMSNumber(smsNumber: string, smsAuthCode?: string | null, handler?: Function): void;
/**
* If your app implements logout functionality, you can call logoutSMSNumber to dissociate the SMS number from the device.
* @param {Function} handler
*/
static logoutSMSNumber(handler?: Function): void;
/**
* Send a notification
* @param {string} notificationObjectString - JSON string payload (see REST API reference)
* @param {(success:object) => void} onSuccess
* @param {(failure:object) => void} onFailure
* @returns void
*/
static postNotification(notificationObjectString: string, onSuccess?: (success: object) => void, onFailure?: (failure: object) => void): void;
/**
* Android Only. iOS provides a standard way to clear notifications by clearing badge count.
* @returns void
*/
static clearOneSignalNotifications(): void;
/**
* Android Only.
* Removes a single OneSignal notification based on its Android notification integer id.
* @param {number} id - notification id to cancel
* @returns void
*/
static removeNotification(id: number): void;
/**
* Android Only.
* Removes all OneSignal notifications based on its Android notification group Id.
* @param {string} id - notification group id to cancel
* @returns void
*/
static removeGroupedNotifications(id: string): void;
/**
* This method can be used to set if launch URLs should be opened in safari or within the application.
* @param {boolean} isEnabled
* @returns
*/
static setLaunchURLsInApp(isEnabled: boolean): void;
/**
* Allows you to use your own system's user ID's to send push notifications to your users.
* @param {string} externalId
* @param {string} externalIdAuthCode?
* @param {(results:object) => void} handler?
* @returns void
*/
static setExternalUserId(externalId: string, handlerOrAuth?: ((results: object) => void) | string, handler?: (results: object) => void): void;
/**
* Removes whatever was set as the current user's external user ID.
* @param {(results:object) => void} handler
* @returns void
*/
static removeExternalUserId(handler?: (results: object) => void): void;
/**
* Sets an In-App Message click event handler.
* @param {(action:InAppMessageAction) => void} handler
* @returns void
*/
static setInAppMessageClickHandler(handler: (action: InAppMessageAction) => void): void;
/**
* Sets the In-App Message lifecycle handler object to run on displaying and/or dismissing an In-App Message.
* @param {InAppMessageLifecycleHandlerObject} handlerObject
* @returns void
*/
static setInAppMessageLifecycleHandler(handlerObject: InAppMessageLifecycleHandlerObject): void;
/**
* Add an In-App Message Trigger.
* @param {string} key
* @param {string | number | boolean} value
* @returns void
*/
static addTrigger(key: string, value: string | number | boolean): void;
/**
* Adds Multiple In-App Message Triggers.
* @param {[key: string]: string | number | boolean} triggers
* @returns void
*/
static addTriggers(triggers: {
[key: string]: string | number | boolean;
}): void;
/**
* Removes a list of triggers based on a collection of keys.
* @param {string[]} keys
* @returns void
*/
static removeTriggersForKeys(keys: string[]): void;
/**
* Removes a list of triggers based on a key.
* @param {string} key
* @returns void
*/
static removeTriggerForKey(key: string): void;
/**
* Gets a trigger value for a provided trigger key.
* @param {string} key
* @returns Promise<string | number | boolean | null>
*/
static getTriggerValueForKey(key: string): Promise<string | number | boolean | null>;
/**
* Pause & unpause In-App Messages
* @param {boolean} pause
* @returns void
*/
static pauseInAppMessages(pause: boolean): void;
/**
* Increases the "Count" of this Outcome by 1 and will be counted each time sent.
* @param {string} name
* @param {(event:OutcomeEvent) => void} handler
* @returns void
*/
static sendOutcome(name: string, handler?: (event: OutcomeEvent) => void): void;
/**
* Increases "Count" by 1 only once. This can only be attributed to a single notification.
* @param {string} name
* @param {(event:OutcomeEvent) => void} handler
* @returns void
*/
static sendUniqueOutcome(name: string, handler?: (event: OutcomeEvent) => void): void;
/**
* Increases the "Count" of this Outcome by 1 and the "Sum" by the value. Will be counted each time sent.
* If the method is called outside of an attribution window, it will be unattributed until a new session occurs.
* @param {string} name
* @param {string|number} value
* @param {(event:OutcomeEvent) => void} handler
* @returns void
*/
static sendOutcomeWithValue(name: string, value: string | number, handler?: (event: OutcomeEvent) => void): void;
/**
* Did the user provide privacy consent for GDPR purposes.
* @returns Promise<boolean>
*/
static userProvidedPrivacyConsent(): Promise<boolean>;
/**
* True if the application requires user privacy consent, false otherwise
* @returns Promise<boolean>
*/
static requiresUserPrivacyConsent(): Promise<boolean>;
/**
* For GDPR users, your application should call this method before setting the App ID.
* @param {boolean} required
* @returns void
*/
static setRequiresUserPrivacyConsent(required: boolean): void;
/**
* If your application is set to require the user's privacy consent, you can provide this consent using this method.
* @param {boolean} granted
* @returns void
*/
static provideUserConsent(granted: boolean): void;
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
* @param {LogLevel} nsLogLevel - Sets the logging level to print to the Android LogCat log or Xcode log.
* @param {LogLevel} visualLogLevel - Sets the logging level to show as alert dialogs.
* @returns void
*/
static setLogLevel(nsLogLevel: LogLevel, visualLogLevel: LogLevel): void;
/**
* Clears all handlers and observers.
* @returns void
*/
static clearHandlers(): void;
function exitLiveActivity(activityId: string, handler?: Function): void;
/** Clears all handlers and observers. */
function clearHandlers(): void;
namespace Debug {
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
* @param {LogLevel} nsLogLevel - Sets the logging level to print to the Android LogCat log or Xcode log.
*/
function setLogLevel(nsLogLevel: LogLevel): void;
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
* @param {LogLevel} visualLogLevel - Sets the logging level to show as alert dialogs.
*/
function setAlertLevel(visualLogLevel: LogLevel): void;
}
namespace User {
namespace PushSubscription {
/** Add a callback that fires when the OneSignal subscription state changes. */
function addChangeHandler(handler: (event: PushSubscription) => void): void;
/** Clears current subscription observers. */
function removeChangeHandler(): void;
/** The readonly push subscription ID */
function getPushSubscriptionId(): string;
/** The readonly push subscription token */
function getPushSubscriptionToken(): string;
/**
* Gets a boolean value indicating whether the current user is opted in to push notifications.
* This returns true when the app has notifications permission and optOut is not called.
* Note: Does not take into account the existence of the subscription ID and push token.
* This boolean may return true but push notifications may still not be received by the user.
*/
function getOptedIn(): boolean;
/** Enable the push notification subscription to OneSignal. */
function optOut(): void;
/** Disable the push notification subscription to OneSignal. */
function optIn(): void;
}
/** Explicitly set a 2-character language code for the user. */
function setLanguage(language: string): void;
/** Set an alias for the current user. If this alias label already exists on this user, it will be overwritten with the new alias id. */
function addAlias(label: string, id: string): void;
/** Set aliases for the current user. If any alias already exists, it will be overwritten to the new values. */
function addAliases(aliases: object): void;
/** Remove an alias from the current user. */
function removeAlias(label: string): void;
/** Remove aliases from the current user. */
function removeAliases(labels: string[]): void;
/** Add a new email subscription to the current user. */
function addEmail(email: string): void;
/**
* Remove an email subscription from the current user. Returns false if the specified email does not exist on the user within the SDK,
* and no request will be made.
*/
function removeEmail(email: string): void;
/** Add a new SMS subscription to the current user. */
function addSms(smsNumber: string): void;
/**
* Remove an SMS subscription from the current user. Returns false if the specified SMS number does not exist on the user within the SDK,
* and no request will be made.
*/
function removeSms(smsNumber: string): void;
/**
* Add a tag for the current user. Tags are key:value pairs used as building blocks for targeting specific users and/or personalizing
* messages. If the tag key already exists, it will be replaced with the value provided here.
*/
function addTag(key: string, value: string): void;
/**
* Add multiple tags for the current user. Tags are key:value pairs used as building blocks for targeting
* specific users and/or personalizing messages. If the tag key already exists, it will be replaced with
* the value provided here.
*/
function addTags(tags: object): void;
/** Remove the data tag with the provided key from the current user. */
function removeTag(key: string): void;
/** Remove multiple tags with the provided keys from the current user. */
function removeTags(keys: string[]): void;
}
namespace Notifications {
/**
* Whether this app has push notification permission. Returns true if the user has accepted permissions,
* or if the app has ephemeral or provisional permission.
*/
function hasPermission(): boolean;
/**
* Prompt the user for permission to receive push notifications. This will display the native system prompt to request push
* notification permission. Use the fallbackToSettings parameter to prompt to open the settings app if a user has already
* declined push permissions.
*/
function requestPermission(fallbackToSettings: boolean): Promise<boolean>;
/**
* Whether attempting to request notification permission will show a prompt. Returns true if the device has not been prompted for push
* notification permission already.
*/
function canRequestPermission(): Promise<boolean>;
/**
* Instead of having to prompt the user for permission to send them push notifications, your app can request provisional authorization.
* For more information: https://documentation.onesignal.com/docs/ios-customizations#provisional-push-notifications
* @param {(response:{accepted:boolean})=>void} handler
*/
function registerForProvisionalAuthorization(handler: (response: boolean) => void): void;
/** Add a callback that fires when the native push permission changes. */
function addPermissionChangedHandler(observer: (event: {
permission: boolean;
}) => void): void;
/** Remove permission observer that have been previously added. */
function removePermissionChangedHandler(): void;
/** Sets a handler that will run whenever a notification is opened by the user. */
function setNotificationClickHandler(handler: (openedEvent: OpenedEvent) => void): void;
/**
* Sets the handler to run before displaying a notification while the app is in focus. Use this handler to read notification
* data and change it or decide if the notification should show or not.
* Note: this runs after the Notification Service Extension which can be used to modify the notification before showing it.
*/
function setNotificationWillShowInForegroundHandler(handler: (event: NotificationReceivedEvent) => void): void;
/**
* Removes all OneSignal notifications.
* Android Only. iOS provides a standard way to clear notifications by clearing badge count.
*/
function clearAll(): void;
/**
* Android Only.
* Removes a single OneSignal notification based on its Android notification integer id.
*/
function removeNotification(id: number): void;
/**
* Android Only.
* Removes all OneSignal notifications based on its Android notification group Id.
* @param {string} id - notification group id to cancel
*/
function removeGroupedNotifications(id: string): void;
}
namespace InAppMessages {
/** Set the in-app message click handler. */
function setClickHandler(handler: (action: InAppMessageAction) => void): void;
/** Set the in-app message lifecycle handler. */
function setLifecycleHandler(handlerObject: InAppMessageLifecycleHandlerObject): void;
/**
* Add a trigger for the current user. Triggers are currently explicitly used to determine whether a specific IAM should be
* displayed to the user.
*/
function addTrigger(key: string, value: string | number | boolean): void;
/**
* Add multiple triggers for the current user. Triggers are currently explicitly used to determine whether a specific IAM should
* be displayed to the user.
*/
function addTriggers(triggers: {
[key: string]: string | number | boolean;
}): void;
/** Remove the trigger with the provided key from the current user. */
function removeTrigger(key: string): void;
/** Remove multiple triggers from the current user. */
function removeTriggers(keys: string[]): void;
/** Clear all triggers from the current user. */
function clearTriggers(): void;
/**
* Set whether in-app messaging is currently paused.
* When set to true no IAM will be presented to the user regardless of whether they qualify for them.
* When set to 'false` any IAMs the user qualifies for will be presented to the user at the appropriate time.
*/
function setPaused(pause: boolean): void;
/** Whether in-app messaging is currently paused. */
function getPaused(): Promise<boolean>;
}
namespace Location {
/** Prompts the user for location permissions to allow geotagging from the OneSignal dashboard. */
function requestPermission(): void;
/** Disable or enable location collection (defaults to enabled if your app has location permission). */
function setShared(shared: boolean): void;
/**
* Checks if location collection is enabled or disabled.
* @param {(value: boolean) => void} handler
*/
function isShared(): Promise<boolean>;
}
namespace Session {
/** Increases the "Count" of this Outcome by 1 and will be counted each time sent. */
function addOutcome(name: string): void;
/** Increases "Count" by 1 only once. This can only be attributed to a single notification. */
function addUniqueOutcome(name: string): void;
/**
* Increases the "Count" of this Outcome by 1 and the "Sum" by the value. Will be counted each time sent.
* If the method is called outside of an attribution window, it will be unattributed until a new session occurs.
*/
function addOutcomeWithValue(name: string, value: string | number): void;
}
}
export { ChangeEvent, PermissionChange, SubscriptionChange, EmailSubscriptionChange, SMSSubscriptionChange, NotificationReceivedEvent, OpenedEvent, InAppMessage, InAppMessageAction, InAppMessageLifecycleHandlerObject, OutcomeEvent, DeviceState, };
export { NotificationReceivedEvent, OpenedEvent, InAppMessage, InAppMessageAction, InAppMessageLifecycleHandlerObject, OutcomeEvent, };
export { default as OSNotification } from './OSNotification';
export { OpenedEventAction, OpenedEventActionType, } from './models/NotificationEvents';
export { IosPermissionStatus, ObserverChangeEvent, } from './models/Subscription';
export { IosPermissionStatus } from './models/Subscription';

@@ -42,3 +42,3 @@ 'use strict';

Object.defineProperty(exports, "__esModule", { value: true });
exports.NotificationReceivedEvent = void 0;
exports.NotificationReceivedEvent = exports.OneSignal = void 0;
var react_native_1 = require("react-native");

@@ -52,234 +52,133 @@ var EventManager_1 = __importDefault(require("./events/EventManager"));

var eventManager = new EventManager_1.default(RNOneSignal);
var OneSignal = /** @class */ (function () {
function OneSignal() {
// Internal wrapper notification permission state that is being updated by the permission change handler.
var notificationPermission = false;
// Internal wrapper push subscription state that is being updated by the subscription change handler.
var pushSubscription = {
id: '',
token: '',
optedIn: false,
};
function setNotificationPermissionChangeHandler() {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
OneSignal.Notifications.addPermissionChangedHandler(function (granted) {
notificationPermission = granted.permission;
});
return [4 /*yield*/, RNOneSignal.hasNotificationPermission()];
case 1:
notificationPermission = _a.sent();
return [2 /*return*/];
}
});
});
}
function setPushSubscriptionChangeHandler() {
return __awaiter(this, void 0, void 0, function () {
var _a, _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
OneSignal.User.PushSubscription.addChangeHandler(function (subscriptionChange) {
pushSubscription = subscriptionChange;
});
_a = pushSubscription;
return [4 /*yield*/, RNOneSignal.getPushSubscriptionId()];
case 1:
_a.id = _d.sent();
_b = pushSubscription;
return [4 /*yield*/, RNOneSignal.getPushSubscriptionToken()];
case 2:
_b.token = _d.sent();
_c = pushSubscription;
return [4 /*yield*/, RNOneSignal.getOptedIn()];
case 3:
_c.optedIn = _d.sent();
return [2 /*return*/];
}
});
});
}
var OneSignal;
(function (OneSignal) {
/** Initializes the OneSignal SDK. This should be called during startup of the application. */
function initialize(appId) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.initialize(appId);
setNotificationPermissionChangeHandler();
setPushSubscriptionChangeHandler();
}
/* I N I T I A L I Z A T I O N */
OneSignal.initialize = initialize;
/**
* Completes OneSignal initialization by setting the OneSignal Application ID.
* @param {string} appId
* @returns void
* If your integration is user-centric, or you want the ability to identify the user beyond the current device, the
* login method should be called to identify the user.
*/
OneSignal.setAppId = function (appId) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
function login(externalId) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
}
RNOneSignal.setAppId(appId);
};
/* O B S E R V E R S */
RNOneSignal.login(externalId);
}
OneSignal.login = login;
/**
* Add a callback that fires when the native push permission changes.
* @param {(event:ChangeEvent<PermissionChange>) => void} observer
* @returns void
* Once (or if) the user is no longer identifiable in your app (i.e. they logged out), the logout method should be
* called.
*/
OneSignal.addPermissionObserver = function (observer) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
function logout() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
}
helpers_1.isValidCallback(observer);
RNOneSignal.addPermissionObserver();
eventManager.addEventHandler(events_1.PERMISSION_CHANGED, observer);
};
/**
* Clears current permission observers.
* @returns void
*/
OneSignal.clearPermissionObservers = function () {
RNOneSignal.logout();
}
OneSignal.logout = logout;
/** True if the application requires user privacy consent, false otherwise. */
function getRequiresPrivacyConsent() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
return Promise.reject(new Error('OneSignal native module not loaded'));
}
RNOneSignal.removePermissionObserver();
eventManager.clearEventHandler(events_1.PERMISSION_CHANGED);
};
/**
* Add a callback that fires when the OneSignal subscription state changes.
* @param {(event:ChangeEvent<SubscriptionChange>) => void} observer
* @returns void
*/
OneSignal.addSubscriptionObserver = function (observer) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return RNOneSignal.getRequiresPrivacyConsent();
}
OneSignal.getRequiresPrivacyConsent = getRequiresPrivacyConsent;
/** For GDPR users, your application should call this method before setting the App ID. */
function setRequiresPrivacyConsent(required) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
}
helpers_1.isValidCallback(observer);
RNOneSignal.addSubscriptionObserver();
eventManager.addEventHandler(events_1.SUBSCRIPTION_CHANGED, observer);
};
/**
* Clears current subscription observers.
* @returns void
*/
OneSignal.clearSubscriptionObservers = function () {
RNOneSignal.setRequiresPrivacyConsent(required);
}
OneSignal.setRequiresPrivacyConsent = setRequiresPrivacyConsent;
/** Indicates whether privacy consent has been granted. */
function getPrivacyConsent() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
return Promise.reject(new Error('OneSignal native module not loaded'));
}
RNOneSignal.removeSubscriptionObserver();
eventManager.clearEventHandler(events_1.SUBSCRIPTION_CHANGED);
};
return RNOneSignal.getPrivacyConsent();
}
OneSignal.getPrivacyConsent = getPrivacyConsent;
/**
* Add a callback that fires when the OneSignal email subscription changes.
* @param {(event:ChangeEvent<EmailSubscriptionChange>) => void} observer
* @returns void
* If your application is set to require the user's privacy consent, you can provide this consent using this method.
* Indicates whether privacy consent has been granted. This field is only relevant when the application has opted
* into data privacy protections.
*/
OneSignal.addEmailSubscriptionObserver = function (observer) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
function setPrivacyConsent(granted) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
}
helpers_1.isValidCallback(observer);
RNOneSignal.addEmailSubscriptionObserver();
eventManager.addEventHandler(events_1.EMAIL_SUBSCRIPTION_CHANGED, observer);
};
/**
* Clears current email subscription observers.
* @returns void
*/
OneSignal.clearEmailSubscriptionObservers = function () {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
RNOneSignal.setPrivacyConsent(granted);
}
OneSignal.setPrivacyConsent = setPrivacyConsent;
/** This method can be used to set if launch URLs should be opened in safari or within the application. */
function setLaunchURLsInApp(isEnabled) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
}
RNOneSignal.removeEmailSubscriptionObserver();
eventManager.clearEventHandler(events_1.EMAIL_SUBSCRIPTION_CHANGED);
};
/**
* Add a callback that fires when the OneSignal sms subscription changes.
* @param {(event:ChangeEvent<SMSSubscriptionChange>) => void} observer
* @returns void
*/
OneSignal.addSMSSubscriptionObserver = function (observer) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
helpers_1.isValidCallback(observer);
RNOneSignal.addSMSSubscriptionObserver();
eventManager.addEventHandler(events_1.SMS_SUBSCRIPTION_CHANGED, observer);
};
/**
* Clears current SMS subscription observers.
* @returns void
*/
OneSignal.clearSMSSubscriptionObservers = function () {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.removeSMSSubscriptionObserver();
eventManager.clearEventHandler(events_1.SMS_SUBSCRIPTION_CHANGED);
};
/* H A N D L E R S */
/**
* Sets the handler that fires before the notification is displayed
* Callback parameter is a `NotificationReceivedEvent` with:
* - notification data
* - `complete` function that accepts the `NotificationReceivedEvent`
* @param {(event:NotificationReceivedEvent) => void} handler
*/
OneSignal.setNotificationWillShowInForegroundHandler = function (handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
helpers_1.isValidCallback(handler);
RNOneSignal.setNotificationWillShowInForegroundHandler();
eventManager.setEventHandler(events_1.NOTIFICATION_WILL_SHOW, handler);
};
/**
* Set the callback to run on notification open.
* @param {(openedEvent:OpenedEvent) => void} handler
* @returns void
*/
OneSignal.setNotificationOpenedHandler = function (handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
helpers_1.isValidCallback(handler);
RNOneSignal.setNotificationOpenedHandler();
eventManager.setEventHandler(events_1.NOTIFICATION_OPENED, handler);
};
/* R E G I S T R A T I O N E T C */
/**
* Prompts the user for push notifications permission in iOS and Android 13+.
* Use the fallbackToSettings parameter to prompt to open the settings app if a user has already declined push permissions.
*
* Call with promptForPushNotificationsWithUserResponse(fallbackToSettings?, handler?)
*
* Recommended: Do not use and instead follow: https://documentation.onesignal.com/docs/ios-push-opt-in-prompt.
* @param {boolean} fallbackToSettings
* @param {(response:boolean) => void} handler
* @returns void
*/
OneSignal.promptForPushNotificationsWithUserResponse = function (fallbackToSettingsOrHandler, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
var fallbackToSettings = false;
if (typeof fallbackToSettingsOrHandler === 'function') {
// Method was called like promptForPushNotificationsWithUserResponse(handler: function)
handler = fallbackToSettingsOrHandler;
}
else if (typeof fallbackToSettingsOrHandler === 'boolean') {
// Method was called like promptForPushNotificationsWithUserResponse(fallbackToSettings: boolean, handler?: function)
fallbackToSettings = fallbackToSettingsOrHandler;
}
// Else method was called like promptForPushNotificationsWithUserResponse(), no need to modify
if (!handler && react_native_1.Platform.OS === 'ios') {
handler = function () { };
}
RNOneSignal.promptForPushNotificationsWithUserResponse(fallbackToSettings, handler);
};
/**
* Only applies to iOS (does nothing on Android as it always silently registers)
* Request for Direct-To-History push notification authorization
*
* For more information: https://documentation.onesignal.com/docs/ios-customizations#provisional-push-notifications
*
* @param {(response:boolean) => void} handler
* @returns void
*/
OneSignal.registerForProvisionalAuthorization = function (handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (react_native_1.Platform.OS === 'ios') {
helpers_1.isValidCallback(handler);
RNOneSignal.registerForProvisionalAuthorization(handler);
RNOneSignal.setLaunchURLsInApp(isEnabled);
}
else {
console.log('registerForProvisionalAuthorization: this function is not supported on Android');
console.log('setLaunchURLsInApp: this function is not supported on Android');
}
};
/**
* Disable the push notification subscription to OneSignal.
* @param {boolean} disable
* @returns void
*/
OneSignal.disablePush = function (disable) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
}
OneSignal.setLaunchURLsInApp = setLaunchURLsInApp;
/** Associates a temporary push token with an Activity ID on the OneSignal server. */
function enterLiveActivity(activityId, token, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
}
RNOneSignal.disablePush(disable);
};
/**
* Android Only. If notifications are disabled for your application, unsubscribe the user from OneSignal.
* @param {boolean} unsubscribe
* @returns void
*/
OneSignal.unsubscribeWhenNotificationsAreDisabled = function (unsubscribe) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (react_native_1.Platform.OS === 'android') {
RNOneSignal.unsubscribeWhenNotificationsAreDisabled(unsubscribe);
}
else {
console.log('unsubscribeWhenNotificationsAreDisabled: this function is not supported on iOS');
}
};
/* L I V E A C T I V I T Y */
/**
* Associates a temporary push token with an Activity ID on the OneSignal server.
* @param {string} activityId
* @param {string} token
* @param {Function} handler
* @returns void
*/
OneSignal.enterLiveActivity = function (activityId, token, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (!handler) {

@@ -292,13 +191,10 @@ handler = function () { };

}
};
}
OneSignal.enterLiveActivity = enterLiveActivity;
/**
* Deletes activityId associated temporary push token on the OneSignal server.
* @param {string} activityId
* @param {Function} handler
* @returns void
*/
OneSignal.exitLiveActivity = function (activityId, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
function exitLiveActivity(activityId, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
}
if (!handler) {

@@ -311,584 +207,513 @@ handler = function () { };

}
};
/* L O C A T I O N */
/**
* True if the application has location share activated, false otherwise
* @returns Promise<boolean>
*/
OneSignal.isLocationShared = function () {
// must return a promise
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return Promise.resolve(false);
}
return RNOneSignal.isLocationShared();
};
/**
* Disable or enable location collection (defaults to enabled if your app has location permission).
* @param {boolean} shared
* @returns void
*/
OneSignal.setLocationShared = function (shared) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
}
OneSignal.exitLiveActivity = exitLiveActivity;
/** Clears all handlers and observers. */
function clearHandlers() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
eventManager.clearHandlers();
}
OneSignal.clearHandlers = clearHandlers;
var Debug;
(function (Debug) {
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
* @param {LogLevel} nsLogLevel - Sets the logging level to print to the Android LogCat log or Xcode log.
*/
function setLogLevel(nsLogLevel) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.setLogLevel(nsLogLevel);
}
RNOneSignal.setLocationShared(shared);
};
/**
* Prompts the user for location permissions to allow geotagging from the OneSignal dashboard.
* @returns void
*/
OneSignal.promptLocation = function () {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
Debug.setLogLevel = setLogLevel;
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
* @param {LogLevel} visualLogLevel - Sets the logging level to show as alert dialogs.
*/
function setAlertLevel(visualLogLevel) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.setAlertLevel(visualLogLevel);
}
//Supported in both iOS & Android
RNOneSignal.promptLocation();
};
/* D E V I C E I N F O */
/**
* Gets the device state.
* This method returns a "snapshot" of the device state for when it was called.
* @returns Promise<DeviceState | null>
*/
OneSignal.getDeviceState = function () {
return __awaiter(this, void 0, void 0, function () {
var deviceState;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return [2 /*return*/, Promise.resolve(null)];
}
return [4 /*yield*/, RNOneSignal.getDeviceState()];
case 1:
deviceState = _a.sent();
if (react_native_1.Platform.OS === 'android') {
deviceState.hasNotificationPermission =
deviceState.areNotificationsEnabled;
delete deviceState.areNotificationsEnabled;
}
return [2 /*return*/, deviceState];
Debug.setAlertLevel = setAlertLevel;
})(Debug = OneSignal.Debug || (OneSignal.Debug = {}));
var User;
(function (User) {
var PushSubscription;
(function (PushSubscription) {
/** Add a callback that fires when the OneSignal subscription state changes. */
function addChangeHandler(handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
helpers_1.isValidCallback(handler);
RNOneSignal.addPushSubscriptionChangeHandler();
eventManager.addEventHandler(events_1.SUBSCRIPTION_CHANGED, handler);
}
PushSubscription.addChangeHandler = addChangeHandler;
/** Clears current subscription observers. */
function removeChangeHandler() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.removePushSubscriptionChangeHandler();
eventManager.clearEventHandler(events_1.SUBSCRIPTION_CHANGED);
}
PushSubscription.removeChangeHandler = removeChangeHandler;
/** The readonly push subscription ID */
function getPushSubscriptionId() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return '';
}
});
});
};
/**
* Allows you to set the app defined language with the OneSignal SDK.
* @param {string} language
* @param {(success:object) => void} onSuccess
* @param {(failure:object) => void} onFailure
* @returns void
*/
OneSignal.setLanguage = function (language, onSuccess, onFailure) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
return pushSubscription.id;
}
PushSubscription.getPushSubscriptionId = getPushSubscriptionId;
/** The readonly push subscription token */
function getPushSubscriptionToken() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return '';
}
return pushSubscription.token;
}
PushSubscription.getPushSubscriptionToken = getPushSubscriptionToken;
/**
* Gets a boolean value indicating whether the current user is opted in to push notifications.
* This returns true when the app has notifications permission and optOut is not called.
* Note: Does not take into account the existence of the subscription ID and push token.
* This boolean may return true but push notifications may still not be received by the user.
*/
function getOptedIn() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return false;
}
return pushSubscription.optedIn;
}
PushSubscription.getOptedIn = getOptedIn;
/** Enable the push notification subscription to OneSignal. */
function optOut() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.optOut();
}
PushSubscription.optOut = optOut;
/** Disable the push notification subscription to OneSignal. */
function optIn() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.optIn();
}
PushSubscription.optIn = optIn;
})(PushSubscription = User.PushSubscription || (User.PushSubscription = {}));
/** Explicitly set a 2-character language code for the user. */
function setLanguage(language) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.setLanguage(language);
}
if (!onSuccess) {
onSuccess = function () { };
User.setLanguage = setLanguage;
/** Set an alias for the current user. If this alias label already exists on this user, it will be overwritten with the new alias id. */
function addAlias(label, id) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.addAlias(label, id);
}
if (!onFailure) {
onFailure = function () { };
User.addAlias = addAlias;
/** Set aliases for the current user. If any alias already exists, it will be overwritten to the new values. */
function addAliases(aliases) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.addAliases(aliases);
}
RNOneSignal.setLanguage(language, onSuccess, onFailure);
};
/* T A G S */
/**
* Tag a user based on an app event of your choosing so they can be targeted later via segments.
* @param {string} key
* @param {string} value
* @returns void
*/
OneSignal.sendTag = function (key, value) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
User.addAliases = addAliases;
/** Remove an alias from the current user. */
function removeAlias(label) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.removeAlias(label);
}
if (!key || (!value && value !== '')) {
console.error('OneSignal: sendTag: must include a key and a value');
User.removeAlias = removeAlias;
/** Remove aliases from the current user. */
function removeAliases(labels) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.removeAliases(labels);
}
RNOneSignal.sendTag(key, value);
};
/**
* Tag a user with multiple tags based on an app event of your choosing so they can be targeted later via segments.
* @param {[key: string]: string} tags
* @returns void
*/
OneSignal.sendTags = function (tags) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
User.removeAliases = removeAliases;
/** Add a new email subscription to the current user. */
function addEmail(email) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.addEmail(email);
}
var keys = Object.keys(tags);
if (keys.length === 0) {
console.error("OneSignal: sendTags: argument must be of type object of the form { key : 'value' }");
User.addEmail = addEmail;
/**
* Remove an email subscription from the current user. Returns false if the specified email does not exist on the user within the SDK,
* and no request will be made.
*/
function removeEmail(email) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.removeEmail(email);
}
RNOneSignal.sendTags(tags || {});
};
/**
* Retrieve a list of tags that have been set on the user from the OneSignal server.
* @param {(tags: {[key: string]: string} | null) => void} handler
* @returns void
*/
OneSignal.getTags = function (handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
User.removeEmail = removeEmail;
/** Add a new SMS subscription to the current user. */
function addSms(smsNumber) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.addSms(smsNumber);
}
RNOneSignal.getTags(handler);
};
/**
* Deletes a single tag that was previously set on a user.
* @param {string} key
* @returns void
*/
OneSignal.deleteTag = function (key) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
User.addSms = addSms;
/**
* Remove an SMS subscription from the current user. Returns false if the specified SMS number does not exist on the user within the SDK,
* and no request will be made.
*/
function removeSms(smsNumber) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.removeSms(smsNumber);
}
if (typeof key !== 'string') {
console.error('OneSignal: deleteTag: key argument must be of type string');
User.removeSms = removeSms;
/**
* Add a tag for the current user. Tags are key:value pairs used as building blocks for targeting specific users and/or personalizing
* messages. If the tag key already exists, it will be replaced with the value provided here.
*/
function addTag(key, value) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
if (!key || (!value && value !== '')) {
console.error('OneSignal: sendTag: must include a key and a value');
return;
}
RNOneSignal.addTag(key, value);
}
RNOneSignal.deleteTags([key]);
};
/**
* Deletes multiple tags that were previously set on a user.
* @param {string[]} keys
*/
OneSignal.deleteTags = function (keys) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
User.addTag = addTag;
/**
* Add multiple tags for the current user. Tags are key:value pairs used as building blocks for targeting
* specific users and/or personalizing messages. If the tag key already exists, it will be replaced with
* the value provided here.
*/
function addTags(tags) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
if (!tags || Object.keys(tags).length === 0) {
console.error('OneSignal: addTags: argument must be of type object of the form { key : "value" }');
return;
}
RNOneSignal.addTags(tags);
}
if (!Array.isArray(keys)) {
console.error('OneSignal: deleteTags: argument must be of array type');
User.addTags = addTags;
/** Remove the data tag with the provided key from the current user. */
function removeTag(key) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
if (typeof key !== 'string') {
console.error('OneSignal: removeTag: key argument must be of type string');
return;
}
RNOneSignal.removeTags([key]);
}
RNOneSignal.deleteTags(keys);
};
/* E M A I L */
/**
* Allows you to set the user's email address with the OneSignal SDK.
* @param {string} email
* @param {string} emailAuthCode
* @param {Function} handler
* @returns void
*/
OneSignal.setEmail = function (email, emailAuthCode, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
User.removeTag = removeTag;
/** Remove multiple tags with the provided keys from the current user. */
function removeTags(keys) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
if (!Array.isArray(keys)) {
console.error('OneSignal: removeTags: argument must be of array type');
return;
}
RNOneSignal.removeTags(keys);
}
if (emailAuthCode === undefined) {
emailAuthCode = null;
User.removeTags = removeTags;
})(User = OneSignal.User || (OneSignal.User = {}));
var Notifications;
(function (Notifications) {
/**
* Whether this app has push notification permission. Returns true if the user has accepted permissions,
* or if the app has ephemeral or provisional permission.
*/
function hasPermission() {
return notificationPermission;
}
// Android workaround for the current issue of callback fired more than once
if (!handler && react_native_1.Platform.OS === 'ios') {
handler = function () { };
Notifications.hasPermission = hasPermission;
/**
* Prompt the user for permission to receive push notifications. This will display the native system prompt to request push
* notification permission. Use the fallbackToSettings parameter to prompt to open the settings app if a user has already
* declined push permissions.
*/
function requestPermission(fallbackToSettings) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return Promise.reject(new Error('OneSignal native module not loaded'));
}
return RNOneSignal.requestNotificationPermission(fallbackToSettings);
}
RNOneSignal.setEmail(email, emailAuthCode, handler);
};
/**
* If your app implements logout functionality, you can call logoutEmail to dissociate the email from the device.
* @param {Function} handler
*/
OneSignal.logoutEmail = function (handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
Notifications.requestPermission = requestPermission;
/**
* Whether attempting to request notification permission will show a prompt. Returns true if the device has not been prompted for push
* notification permission already.
*/
function canRequestPermission() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return Promise.reject(new Error('OneSignal native module not loaded'));
}
return RNOneSignal.canRequestNotificationPermission();
}
// Android workaround for the current issue of callback fired more than once
if (!handler && react_native_1.Platform.OS === 'ios') {
handler = function () { };
Notifications.canRequestPermission = canRequestPermission;
/**
* Instead of having to prompt the user for permission to send them push notifications, your app can request provisional authorization.
* For more information: https://documentation.onesignal.com/docs/ios-customizations#provisional-push-notifications
* @param {(response:{accepted:boolean})=>void} handler
*/
function registerForProvisionalAuthorization(handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
if (react_native_1.Platform.OS === 'ios') {
helpers_1.isValidCallback(handler);
RNOneSignal.registerForProvisionalAuthorization(handler);
}
else {
console.log('registerForProvisionalAuthorization: this function is not supported on Android');
}
}
RNOneSignal.logoutEmail(handler);
};
/* S M S */
/**
* Allows you to set the user's SMS number with the OneSignal SDK.
* @param {string} smsNumber
* @param {string} smsAuthCode
* @param {Function} handler
* @returns void
*/
OneSignal.setSMSNumber = function (smsNumber, smsAuthCode, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
Notifications.registerForProvisionalAuthorization = registerForProvisionalAuthorization;
/** Add a callback that fires when the native push permission changes. */
function addPermissionChangedHandler(observer) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
helpers_1.isValidCallback(observer);
RNOneSignal.addPermissionChangedHandler();
eventManager.addEventHandler(events_1.PERMISSION_CHANGED, observer);
}
if (smsAuthCode === undefined) {
smsAuthCode = null;
Notifications.addPermissionChangedHandler = addPermissionChangedHandler;
/** Remove permission observer that have been previously added. */
function removePermissionChangedHandler() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.removePermissionChangedHandler();
eventManager.clearEventHandler(events_1.PERMISSION_CHANGED);
}
// Android workaround for the current issue of callback fired more than once
if (!handler && react_native_1.Platform.OS === 'ios') {
handler = function () { };
Notifications.removePermissionChangedHandler = removePermissionChangedHandler;
/** Sets a handler that will run whenever a notification is opened by the user. */
function setNotificationClickHandler(handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
helpers_1.isValidCallback(handler);
RNOneSignal.setNotificationClickHandler();
eventManager.setEventHandler(events_1.NOTIFICATION_CLICKED, handler);
}
RNOneSignal.setSMSNumber(smsNumber, smsAuthCode, handler);
};
/**
* If your app implements logout functionality, you can call logoutSMSNumber to dissociate the SMS number from the device.
* @param {Function} handler
*/
OneSignal.logoutSMSNumber = function (handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
Notifications.setNotificationClickHandler = setNotificationClickHandler;
/**
* Sets the handler to run before displaying a notification while the app is in focus. Use this handler to read notification
* data and change it or decide if the notification should show or not.
* Note: this runs after the Notification Service Extension which can be used to modify the notification before showing it.
*/
function setNotificationWillShowInForegroundHandler(handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
helpers_1.isValidCallback(handler);
RNOneSignal.setNotificationWillShowInForegroundHandler();
eventManager.setEventHandler(events_1.NOTIFICATION_WILL_SHOW, handler);
}
// Android workaround for the current issue of callback fired more than once
if (!handler && react_native_1.Platform.OS === 'ios') {
handler = function () { };
Notifications.setNotificationWillShowInForegroundHandler = setNotificationWillShowInForegroundHandler;
/**
* Removes all OneSignal notifications.
* Android Only. iOS provides a standard way to clear notifications by clearing badge count.
*/
function clearAll() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.clearAllNotifications();
}
RNOneSignal.logoutSMSNumber(handler);
};
/* N O T I F I C A T I O N S */
/**
* Send a notification
* @param {string} notificationObjectString - JSON string payload (see REST API reference)
* @param {(success:object) => void} onSuccess
* @param {(failure:object) => void} onFailure
* @returns void
*/
OneSignal.postNotification = function (notificationObjectString, onSuccess, onFailure) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
Notifications.clearAll = clearAll;
/**
* Android Only.
* Removes a single OneSignal notification based on its Android notification integer id.
*/
function removeNotification(id) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
if (react_native_1.Platform.OS === 'android') {
RNOneSignal.removeNotification(id);
}
else {
console.log('removeNotification: this function is not supported on iOS');
}
}
if (!onSuccess) {
onSuccess = function () { };
Notifications.removeNotification = removeNotification;
/**
* Android Only.
* Removes all OneSignal notifications based on its Android notification group Id.
* @param {string} id - notification group id to cancel
*/
function removeGroupedNotifications(id) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
if (react_native_1.Platform.OS === 'android') {
RNOneSignal.removeGroupedNotifications(id);
}
else {
console.log('removeGroupedNotifications: this function is not supported on iOS');
}
}
if (!onFailure) {
onFailure = function () { };
Notifications.removeGroupedNotifications = removeGroupedNotifications;
})(Notifications = OneSignal.Notifications || (OneSignal.Notifications = {}));
var InAppMessages;
(function (InAppMessages) {
/** Set the in-app message click handler. */
function setClickHandler(handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
helpers_1.isValidCallback(handler);
RNOneSignal.setInAppMessageClickHandler();
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_CLICKED, handler);
}
RNOneSignal.postNotification(notificationObjectString, onSuccess, onFailure);
};
/**
* Android Only. iOS provides a standard way to clear notifications by clearing badge count.
* @returns void
*/
OneSignal.clearOneSignalNotifications = function () {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
InAppMessages.setClickHandler = setClickHandler;
/** Set the in-app message lifecycle handler. */
function setLifecycleHandler(handlerObject) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
if (handlerObject.onWillDisplayInAppMessage) {
helpers_1.isValidCallback(handlerObject.onWillDisplayInAppMessage);
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_WILL_DISPLAY, handlerObject.onWillDisplayInAppMessage);
}
if (handlerObject.onDidDisplayInAppMessage) {
helpers_1.isValidCallback(handlerObject.onDidDisplayInAppMessage);
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_DID_DISPLAY, handlerObject.onDidDisplayInAppMessage);
}
if (handlerObject.onWillDismissInAppMessage) {
helpers_1.isValidCallback(handlerObject.onWillDismissInAppMessage);
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_WILL_DISMISS, handlerObject.onWillDismissInAppMessage);
}
if (handlerObject.onDidDismissInAppMessage) {
helpers_1.isValidCallback(handlerObject.onDidDismissInAppMessage);
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_DID_DISMISS, handlerObject.onDidDismissInAppMessage);
}
RNOneSignal.setInAppMessagesLifecycleHandler();
}
if (react_native_1.Platform.OS === 'android') {
RNOneSignal.clearOneSignalNotifications();
InAppMessages.setLifecycleHandler = setLifecycleHandler;
/**
* Add a trigger for the current user. Triggers are currently explicitly used to determine whether a specific IAM should be
* displayed to the user.
*/
function addTrigger(key, value) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
// value can be assigned to `false` so we cannot just check `!value`
if (!key || value == null) {
console.error('OneSignal: addTrigger: must include a key and a value');
}
var trigger = {};
trigger[key] = value;
RNOneSignal.addTriggers(trigger);
}
else {
console.log('clearOneSignalNotifications: this function is not supported on iOS');
InAppMessages.addTrigger = addTrigger;
/**
* Add multiple triggers for the current user. Triggers are currently explicitly used to determine whether a specific IAM should
* be displayed to the user.
*/
function addTriggers(triggers) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
var keys = Object.keys(triggers);
if (keys.length === 0) {
console.error("OneSignal: addTriggers: argument must be an object of the form { key : 'value' }");
}
RNOneSignal.addTriggers(triggers);
}
};
/**
* Android Only.
* Removes a single OneSignal notification based on its Android notification integer id.
* @param {number} id - notification id to cancel
* @returns void
*/
OneSignal.removeNotification = function (id) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
InAppMessages.addTriggers = addTriggers;
/** Remove the trigger with the provided key from the current user. */
function removeTrigger(key) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.removeTrigger(key);
}
if (react_native_1.Platform.OS === 'android') {
RNOneSignal.removeNotification(id);
InAppMessages.removeTrigger = removeTrigger;
/** Remove multiple triggers from the current user. */
function removeTriggers(keys) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.removeTriggers(keys);
}
else {
console.log('removeNotification: this function is not supported on iOS');
InAppMessages.removeTriggers = removeTriggers;
/** Clear all triggers from the current user. */
function clearTriggers() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.clearTriggers();
}
};
/**
* Android Only.
* Removes all OneSignal notifications based on its Android notification group Id.
* @param {string} id - notification group id to cancel
* @returns void
*/
OneSignal.removeGroupedNotifications = function (id) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
InAppMessages.clearTriggers = clearTriggers;
/**
* Set whether in-app messaging is currently paused.
* When set to true no IAM will be presented to the user regardless of whether they qualify for them.
* When set to 'false` any IAMs the user qualifies for will be presented to the user at the appropriate time.
*/
function setPaused(pause) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.paused(pause);
}
if (react_native_1.Platform.OS === 'android') {
RNOneSignal.removeGroupedNotifications(id);
InAppMessages.setPaused = setPaused;
/** Whether in-app messaging is currently paused. */
function getPaused() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return Promise.reject(new Error('OneSignal native module not loaded'));
}
return RNOneSignal.getPaused();
}
else {
console.log('removeGroupedNotifications: this function is not supported on iOS');
InAppMessages.getPaused = getPaused;
})(InAppMessages = OneSignal.InAppMessages || (OneSignal.InAppMessages = {}));
var Location;
(function (Location) {
/** Prompts the user for location permissions to allow geotagging from the OneSignal dashboard. */
function requestPermission() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.requestLocationPermission();
}
};
/**
* This method can be used to set if launch URLs should be opened in safari or within the application.
* @param {boolean} isEnabled
* @returns
*/
OneSignal.setLaunchURLsInApp = function (isEnabled) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
Location.requestPermission = requestPermission;
/** Disable or enable location collection (defaults to enabled if your app has location permission). */
function setShared(shared) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.setLocationShared(shared);
}
if (react_native_1.Platform.OS === 'ios') {
RNOneSignal.setLaunchURLsInApp(isEnabled);
Location.setShared = setShared;
/**
* Checks if location collection is enabled or disabled.
* @param {(value: boolean) => void} handler
*/
function isShared() {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return Promise.reject(new Error('OneSignal native module not loaded'));
}
return RNOneSignal.isLocationShared();
}
else {
console.log('setLaunchURLsInApp: this function is not supported on Android');
Location.isShared = isShared;
})(Location = OneSignal.Location || (OneSignal.Location = {}));
var Session;
(function (Session) {
/** Increases the "Count" of this Outcome by 1 and will be counted each time sent. */
function addOutcome(name) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.addOutcome(name);
}
};
/* E X T E R N A L U S E R I D */
/**
* Allows you to use your own system's user ID's to send push notifications to your users.
* @param {string} externalId
* @param {string} externalIdAuthCode?
* @param {(results:object) => void} handler?
* @returns void
*/
OneSignal.setExternalUserId = function (externalId, handlerOrAuth, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
Session.addOutcome = addOutcome;
/** Increases "Count" by 1 only once. This can only be attributed to a single notification. */
function addUniqueOutcome(name) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.addUniqueOutcome(name);
}
if (typeof handlerOrAuth === 'function') {
RNOneSignal.setExternalUserId(externalId, null, handlerOrAuth);
return;
Session.addUniqueOutcome = addUniqueOutcome;
/**
* Increases the "Count" of this Outcome by 1 and the "Sum" by the value. Will be counted each time sent.
* If the method is called outside of an attribution window, it will be unattributed until a new session occurs.
*/
function addOutcomeWithValue(name, value) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal))
return;
RNOneSignal.addOutcomeWithValue(name, Number(value));
}
if (!handler && react_native_1.Platform.OS === 'ios') {
handler = function () { };
}
RNOneSignal.setExternalUserId(externalId, handlerOrAuth, handler);
};
/**
* Removes whatever was set as the current user's external user ID.
* @param {(results:object) => void} handler
* @returns void
*/
OneSignal.removeExternalUserId = function (handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
// Android workaround for the current issue of callback fired more than once
if (handler === undefined && react_native_1.Platform.OS === 'ios') {
handler = function () { };
}
RNOneSignal.removeExternalUserId(handler);
};
/* I N A P P M E S S A G I N G */
/**
* Sets an In-App Message click event handler.
* @param {(action:InAppMessageAction) => void} handler
* @returns void
*/
OneSignal.setInAppMessageClickHandler = function (handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
helpers_1.isValidCallback(handler);
RNOneSignal.initInAppMessageClickHandlerParams();
RNOneSignal.setInAppMessageClickHandler();
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_CLICKED, handler);
};
/**
* Sets the In-App Message lifecycle handler object to run on displaying and/or dismissing an In-App Message.
* @param {InAppMessageLifecycleHandlerObject} handlerObject
* @returns void
*/
OneSignal.setInAppMessageLifecycleHandler = function (handlerObject) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (handlerObject.onWillDisplayInAppMessage) {
helpers_1.isValidCallback(handlerObject.onWillDisplayInAppMessage);
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_WILL_DISPLAY, handlerObject.onWillDisplayInAppMessage);
}
if (handlerObject.onDidDisplayInAppMessage) {
helpers_1.isValidCallback(handlerObject.onDidDisplayInAppMessage);
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_DID_DISPLAY, handlerObject.onDidDisplayInAppMessage);
}
if (handlerObject.onWillDismissInAppMessage) {
helpers_1.isValidCallback(handlerObject.onWillDismissInAppMessage);
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_WILL_DISMISS, handlerObject.onWillDismissInAppMessage);
}
if (handlerObject.onDidDismissInAppMessage) {
helpers_1.isValidCallback(handlerObject.onDidDismissInAppMessage);
eventManager.setEventHandler(events_1.IN_APP_MESSAGE_DID_DISMISS, handlerObject.onDidDismissInAppMessage);
}
RNOneSignal.setInAppMessageLifecycleHandler();
};
/**
* Add an In-App Message Trigger.
* @param {string} key
* @param {string | number | boolean} value
* @returns void
*/
OneSignal.addTrigger = function (key, value) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
// value can be assigned to `false` so we cannot just check `!value`
if (!key || value == null) {
console.error('OneSignal: addTrigger: must include a key and a value');
}
var trigger = {};
trigger[key] = value;
RNOneSignal.addTriggers(trigger);
};
/**
* Adds Multiple In-App Message Triggers.
* @param {[key: string]: string | number | boolean} triggers
* @returns void
*/
OneSignal.addTriggers = function (triggers) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
var keys = Object.keys(triggers);
if (keys.length === 0) {
console.error("OneSignal: addTriggers: argument must be an object of the form { key : 'value' }");
}
RNOneSignal.addTriggers(triggers);
};
/**
* Removes a list of triggers based on a collection of keys.
* @param {string[]} keys
* @returns void
*/
OneSignal.removeTriggersForKeys = function (keys) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.removeTriggersForKeys(keys);
};
/**
* Removes a list of triggers based on a key.
* @param {string} key
* @returns void
*/
OneSignal.removeTriggerForKey = function (key) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.removeTriggerForKey(key);
};
/**
* Gets a trigger value for a provided trigger key.
* @param {string} key
* @returns Promise<string | number | boolean | null>
*/
OneSignal.getTriggerValueForKey = function (key) {
// must return a promise
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return Promise.resolve(null);
}
return RNOneSignal.getTriggerValueForKey(key);
};
/**
* Pause & unpause In-App Messages
* @param {boolean} pause
* @returns void
*/
OneSignal.pauseInAppMessages = function (pause) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.pauseInAppMessages(pause);
};
/* O U T C O M E S */
/**
* Increases the "Count" of this Outcome by 1 and will be counted each time sent.
* @param {string} name
* @param {(event:OutcomeEvent) => void} handler
* @returns void
*/
OneSignal.sendOutcome = function (name, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (!handler) {
handler = function () { };
}
RNOneSignal.sendOutcome(name, handler);
};
/**
* Increases "Count" by 1 only once. This can only be attributed to a single notification.
* @param {string} name
* @param {(event:OutcomeEvent) => void} handler
* @returns void
*/
OneSignal.sendUniqueOutcome = function (name, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (!handler) {
handler = function () { };
}
RNOneSignal.sendUniqueOutcome(name, handler);
};
/**
* Increases the "Count" of this Outcome by 1 and the "Sum" by the value. Will be counted each time sent.
* If the method is called outside of an attribution window, it will be unattributed until a new session occurs.
* @param {string} name
* @param {string|number} value
* @param {(event:OutcomeEvent) => void} handler
* @returns void
*/
OneSignal.sendOutcomeWithValue = function (name, value, handler) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (!handler) {
handler = function () { };
}
RNOneSignal.sendOutcomeWithValue(name, Number(value), handler);
};
/* P R I V A C Y C O N S E N T */
/**
* Did the user provide privacy consent for GDPR purposes.
* @returns Promise<boolean>
*/
OneSignal.userProvidedPrivacyConsent = function () {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return Promise.resolve(false);
}
//returns a promise
return RNOneSignal.userProvidedPrivacyConsent();
};
/**
* True if the application requires user privacy consent, false otherwise
* @returns Promise<boolean>
*/
OneSignal.requiresUserPrivacyConsent = function () {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return Promise.resolve(false);
}
//returns a promise
return RNOneSignal.requiresUserPrivacyConsent();
};
/**
* For GDPR users, your application should call this method before setting the App ID.
* @param {boolean} required
* @returns void
*/
OneSignal.setRequiresUserPrivacyConsent = function (required) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.setRequiresUserPrivacyConsent(required);
};
/**
* If your application is set to require the user's privacy consent, you can provide this consent using this method.
* @param {boolean} granted
* @returns void
*/
OneSignal.provideUserConsent = function (granted) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.provideUserConsent(granted);
};
/* O T H E R F U N C T I O N S */
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
* @param {LogLevel} nsLogLevel - Sets the logging level to print to the Android LogCat log or Xcode log.
* @param {LogLevel} visualLogLevel - Sets the logging level to show as alert dialogs.
* @returns void
*/
OneSignal.setLogLevel = function (nsLogLevel, visualLogLevel) {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.setLogLevel(nsLogLevel, visualLogLevel);
};
/**
* Clears all handlers and observers.
* @returns void
*/
OneSignal.clearHandlers = function () {
if (!helpers_1.isNativeModuleLoaded(RNOneSignal)) {
return;
}
eventManager.clearHandlers();
};
return OneSignal;
}());
exports.default = OneSignal;
Session.addOutcomeWithValue = addOutcomeWithValue;
})(Session = OneSignal.Session || (OneSignal.Session = {}));
})(OneSignal = exports.OneSignal || (exports.OneSignal = {}));
var OSNotification_1 = require("./OSNotification");
Object.defineProperty(exports, "OSNotification", { enumerable: true, get: function () { return OSNotification_1.default; } });
export declare type IosPermissionStatus = 0 | 1 | 2 | 3 | 4;
export interface DeviceState {
userId: string;
pushToken: string;
emailUserId: string;
emailAddress: string;
smsUserId: string;
smsNumber: string;
isSubscribed: boolean;
isPushDisabled: boolean;
isEmailSubscribed: boolean;
isSMSSubscribed: boolean;
hasNotificationPermission?: boolean;
notificationPermissionStatus?: IosPermissionStatus;
export interface PushSubscription {
id: string;
token: string;
optedIn: boolean;
}
export interface ChangeEvent<ObserverChangeEvent> {
from: ObserverChangeEvent;
to: ObserverChangeEvent;
}
export declare type ObserverChangeEvent = PermissionChange | SubscriptionChange | EmailSubscriptionChange | SMSSubscriptionChange;
export interface PermissionChange {
status?: IosPermissionStatus;
hasPrompted?: boolean;
provisional?: boolean;
areNotificationsEnabled?: boolean;
}
export interface SubscriptionChange {
userId?: string;
pushToken?: string;
isSubscribed: boolean;
isPushDisabled: boolean;
}
export interface EmailSubscriptionChange {
emailAddress?: string;
emailUserId?: string;
isEmailSubscribed: boolean;
}
export interface SMSSubscriptionChange {
smsNumber?: string;
smsUserId?: string;
isSMSSubscribed: boolean;
}
{
"name": "react-native-onesignal",
"version": "4.5.1",
"version": "5.0.0-beta-01",
"description": "React Native OneSignal SDK",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

@@ -25,4 +25,1 @@ <p align="center">

#### Supports:
* Tested from iOS 7 to iOS 13
* Tested from Android 4.0.3 (API level 15) to Android 9 (28)

@@ -12,6 +12,4 @@ import {

NOTIFICATION_WILL_SHOW,
NOTIFICATION_OPENED,
NOTIFICATION_CLICKED,
IN_APP_MESSAGE_CLICKED,
EMAIL_SUBSCRIPTION_CHANGED,
SMS_SUBSCRIPTION_CHANGED,
IN_APP_MESSAGE_WILL_DISPLAY,

@@ -22,3 +20,2 @@ IN_APP_MESSAGE_WILL_DISMISS,

} from './events';
import { ChangeEvent } from '../models/Subscription';
import OSNotification from '../OSNotification';

@@ -30,6 +27,4 @@

NOTIFICATION_WILL_SHOW,
NOTIFICATION_OPENED,
NOTIFICATION_CLICKED,
IN_APP_MESSAGE_CLICKED,
EMAIL_SUBSCRIPTION_CHANGED,
SMS_SUBSCRIPTION_CHANGED,
IN_APP_MESSAGE_WILL_DISPLAY,

@@ -51,3 +46,3 @@ IN_APP_MESSAGE_WILL_DISMISS,

this.oneSignalEventEmitter = new NativeEventEmitter(RNOneSignal);
this.eventHandlerMap = new Map(); // used for setters (single replacable callback)
this.eventHandlerMap = new Map(); // used for setters (single replaceable callback)
this.eventHandlerArrayMap = new Map(); // used for adders (multiple callbacks possible)

@@ -58,3 +53,3 @@ this.listeners = {};

setupListeners(): void {
setupListeners() {
// set up the event emitter and listeners

@@ -70,3 +65,3 @@ if (this.RNOneSignal != null) {

// clear handlers
clearHandlers(): void {
clearHandlers() {
this.eventHandlerMap = new Map();

@@ -83,3 +78,3 @@ this.eventHandlerArrayMap = new Map();

*/
setEventHandler<T>(eventName: string, handler: (event: T) => void): void {
setEventHandler<T>(eventName: string, handler: (event: T) => void) {
this.eventHandlerMap.set(eventName, handler);

@@ -94,6 +89,3 @@ }

*/
addEventHandler<T>(
eventName: string,
handler: (event: ChangeEvent<T>) => void,
): void {
addEventHandler<T>(eventName: string, handler: (event: T) => void) {
let handlerArray = this.eventHandlerArrayMap.get(eventName);

@@ -110,3 +102,3 @@ handlerArray && handlerArray.length > 0

*/
clearEventHandler(eventName: string): void {
clearEventHandler(eventName: string) {
this.eventHandlerArrayMap.delete(eventName);

@@ -113,0 +105,0 @@ }

@@ -1,8 +0,5 @@

// events
export const NOTIFICATION_WILL_SHOW =
'OneSignal-notificationWillShowInForeground';
export const NOTIFICATION_OPENED = 'OneSignal-remoteNotificationOpened';
export const NOTIFICATION_CLICKED = 'OneSignal-notificationClicked';
export const IN_APP_MESSAGE_CLICKED = 'OneSignal-inAppMessageClicked';
// In-App Message lifecycle events
export const IN_APP_MESSAGE_WILL_DISPLAY = 'OneSignal-inAppMessageWillDisplay';

@@ -12,6 +9,3 @@ export const IN_APP_MESSAGE_DID_DISPLAY = 'OneSignal-inAppMessageDidDisplay';

export const IN_APP_MESSAGE_DID_DISMISS = 'OneSignal-inAppMessageDidDismiss';
export const PERMISSION_CHANGED = 'OneSignal-permissionChanged';
export const SUBSCRIPTION_CHANGED = 'OneSignal-subscriptionChanged';
export const EMAIL_SUBSCRIPTION_CHANGED = 'OneSignal-emailSubscriptionChanged';
export const SMS_SUBSCRIPTION_CHANGED = 'OneSignal-smsSubscriptionChanged';

@@ -12,3 +12,3 @@ import { NativeModules } from 'react-native';

complete(notification?: OSNotification): void {
complete(notification?: OSNotification) {
if (!notification) {

@@ -15,0 +15,0 @@ // if the notificationReceivedEvent is null, we want to call the native-side

import invariant from 'invariant';
import { NativeModule } from 'react-native';
import {
PERMISSION_CHANGED,
SUBSCRIPTION_CHANGED,
EMAIL_SUBSCRIPTION_CHANGED,
SMS_SUBSCRIPTION_CHANGED,
} from './events/events';
import { PERMISSION_CHANGED, SUBSCRIPTION_CHANGED } from './events/events';

@@ -19,4 +14,6 @@ export function isValidCallback(handler: Function) {

);
return false;
}
return true;

@@ -33,4 +30,2 @@ }

case SUBSCRIPTION_CHANGED:
case EMAIL_SUBSCRIPTION_CHANGED:
case SMS_SUBSCRIPTION_CHANGED:
return true;

@@ -37,0 +32,0 @@ default:

@@ -6,22 +6,13 @@ 'use strict';

import {
PERMISSION_CHANGED,
SUBSCRIPTION_CHANGED,
IN_APP_MESSAGE_CLICKED,
NOTIFICATION_WILL_SHOW,
NOTIFICATION_OPENED,
EMAIL_SUBSCRIPTION_CHANGED,
SMS_SUBSCRIPTION_CHANGED,
IN_APP_MESSAGE_WILL_DISPLAY,
IN_APP_MESSAGE_WILL_DISMISS,
IN_APP_MESSAGE_DID_DISMISS,
IN_APP_MESSAGE_DID_DISPLAY,
IN_APP_MESSAGE_WILL_DISMISS,
IN_APP_MESSAGE_WILL_DISPLAY,
NOTIFICATION_CLICKED,
NOTIFICATION_WILL_SHOW,
PERMISSION_CHANGED,
SUBSCRIPTION_CHANGED,
} from './events/events';
import {
DeviceState,
ChangeEvent,
PermissionChange,
SubscriptionChange,
EmailSubscriptionChange,
SMSSubscriptionChange,
} from './models/Subscription';
import { PushSubscription } from './models/Subscription';
import NotificationReceivedEvent from './events/NotificationReceivedEvent';

@@ -43,302 +34,120 @@ import { OpenedEvent } from './models/NotificationEvents';

export default class OneSignal {
/* I N I T I A L I Z A T I O N */
// Internal wrapper notification permission state that is being updated by the permission change handler.
let notificationPermission = false;
/**
* Completes OneSignal initialization by setting the OneSignal Application ID.
* @param {string} appId
* @returns void
*/
static setAppId(appId: string): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.setAppId(appId);
}
// Internal wrapper push subscription state that is being updated by the subscription change handler.
let pushSubscription: PushSubscription = {
id: '',
token: '',
optedIn: false,
};
/* O B S E R V E R S */
async function setNotificationPermissionChangeHandler() {
OneSignal.Notifications.addPermissionChangedHandler((granted) => {
notificationPermission = granted.permission;
});
/**
* Add a callback that fires when the native push permission changes.
* @param {(event:ChangeEvent<PermissionChange>) => void} observer
* @returns void
*/
static addPermissionObserver(
observer: (event: ChangeEvent<PermissionChange>) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
isValidCallback(observer);
RNOneSignal.addPermissionObserver();
eventManager.addEventHandler<PermissionChange>(
PERMISSION_CHANGED,
observer,
);
}
notificationPermission = await RNOneSignal.hasNotificationPermission();
}
/**
* Clears current permission observers.
* @returns void
*/
static clearPermissionObservers(): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.removePermissionObserver();
eventManager.clearEventHandler(PERMISSION_CHANGED);
}
async function setPushSubscriptionChangeHandler() {
OneSignal.User.PushSubscription.addChangeHandler((subscriptionChange) => {
pushSubscription = subscriptionChange;
});
/**
* Add a callback that fires when the OneSignal subscription state changes.
* @param {(event:ChangeEvent<SubscriptionChange>) => void} observer
* @returns void
*/
static addSubscriptionObserver(
observer: (event: ChangeEvent<SubscriptionChange>) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
isValidCallback(observer);
RNOneSignal.addSubscriptionObserver();
eventManager.addEventHandler<SubscriptionChange>(
SUBSCRIPTION_CHANGED,
observer,
);
}
pushSubscription.id = await RNOneSignal.getPushSubscriptionId();
pushSubscription.token = await RNOneSignal.getPushSubscriptionToken();
pushSubscription.optedIn = await RNOneSignal.getOptedIn();
}
/**
* Clears current subscription observers.
* @returns void
*/
static clearSubscriptionObservers(): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.removeSubscriptionObserver();
eventManager.clearEventHandler(SUBSCRIPTION_CHANGED);
}
export namespace OneSignal {
/** Initializes the OneSignal SDK. This should be called during startup of the application. */
export function initialize(appId: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Add a callback that fires when the OneSignal email subscription changes.
* @param {(event:ChangeEvent<EmailSubscriptionChange>) => void} observer
* @returns void
*/
static addEmailSubscriptionObserver(
observer: (event: ChangeEvent<EmailSubscriptionChange>) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
isValidCallback(observer);
RNOneSignal.addEmailSubscriptionObserver();
eventManager.addEventHandler<EmailSubscriptionChange>(
EMAIL_SUBSCRIPTION_CHANGED,
observer,
);
RNOneSignal.initialize(appId);
setNotificationPermissionChangeHandler();
setPushSubscriptionChangeHandler();
}
/**
* Clears current email subscription observers.
* @returns void
* If your integration is user-centric, or you want the ability to identify the user beyond the current device, the
* login method should be called to identify the user.
*/
static clearEmailSubscriptionObservers(): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.removeEmailSubscriptionObserver();
eventManager.clearEventHandler(EMAIL_SUBSCRIPTION_CHANGED);
}
export function login(externalId: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Add a callback that fires when the OneSignal sms subscription changes.
* @param {(event:ChangeEvent<SMSSubscriptionChange>) => void} observer
* @returns void
*/
static addSMSSubscriptionObserver(
observer: (event: ChangeEvent<SMSSubscriptionChange>) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
isValidCallback(observer);
RNOneSignal.addSMSSubscriptionObserver();
eventManager.addEventHandler<SMSSubscriptionChange>(
SMS_SUBSCRIPTION_CHANGED,
observer,
);
RNOneSignal.login(externalId);
}
/**
* Clears current SMS subscription observers.
* @returns void
* Once (or if) the user is no longer identifiable in your app (i.e. they logged out), the logout method should be
* called.
*/
static clearSMSSubscriptionObservers(): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.removeSMSSubscriptionObserver();
eventManager.clearEventHandler(SMS_SUBSCRIPTION_CHANGED);
}
export function logout() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/* H A N D L E R S */
/**
* Sets the handler that fires before the notification is displayed
* Callback parameter is a `NotificationReceivedEvent` with:
* - notification data
* - `complete` function that accepts the `NotificationReceivedEvent`
* @param {(event:NotificationReceivedEvent) => void} handler
*/
static setNotificationWillShowInForegroundHandler(
handler: (event: NotificationReceivedEvent) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
isValidCallback(handler);
RNOneSignal.setNotificationWillShowInForegroundHandler();
eventManager.setEventHandler<NotificationReceivedEvent>(
NOTIFICATION_WILL_SHOW,
handler,
);
RNOneSignal.logout();
}
/**
* Set the callback to run on notification open.
* @param {(openedEvent:OpenedEvent) => void} handler
* @returns void
*/
static setNotificationOpenedHandler(
handler: (openedEvent: OpenedEvent) => void,
): void {
/** True if the application requires user privacy consent, false otherwise. */
export function getRequiresPrivacyConsent(): Promise<boolean> {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
return Promise.reject(new Error('OneSignal native module not loaded'));
}
isValidCallback(handler);
RNOneSignal.setNotificationOpenedHandler();
eventManager.setEventHandler<OpenedEvent>(NOTIFICATION_OPENED, handler);
return RNOneSignal.getRequiresPrivacyConsent();
}
/* R E G I S T R A T I O N E T C */
/** For GDPR users, your application should call this method before setting the App ID. */
export function setRequiresPrivacyConsent(required: boolean) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Prompts the user for push notifications permission in iOS and Android 13+.
* Use the fallbackToSettings parameter to prompt to open the settings app if a user has already declined push permissions.
*
* Call with promptForPushNotificationsWithUserResponse(fallbackToSettings?, handler?)
*
* Recommended: Do not use and instead follow: https://documentation.onesignal.com/docs/ios-push-opt-in-prompt.
* @param {boolean} fallbackToSettings
* @param {(response:boolean) => void} handler
* @returns void
*/
static promptForPushNotificationsWithUserResponse(
fallbackToSettingsOrHandler?: boolean | ((response: boolean) => void),
handler?: (response: boolean) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
let fallbackToSettings = false;
if (typeof fallbackToSettingsOrHandler === 'function') {
// Method was called like promptForPushNotificationsWithUserResponse(handler: function)
handler = fallbackToSettingsOrHandler;
} else if (typeof fallbackToSettingsOrHandler === 'boolean') {
// Method was called like promptForPushNotificationsWithUserResponse(fallbackToSettings: boolean, handler?: function)
fallbackToSettings = fallbackToSettingsOrHandler;
}
// Else method was called like promptForPushNotificationsWithUserResponse(), no need to modify
if (!handler && Platform.OS === 'ios') {
handler = function () {};
}
RNOneSignal.promptForPushNotificationsWithUserResponse(
fallbackToSettings,
handler,
);
RNOneSignal.setRequiresPrivacyConsent(required);
}
/**
* Only applies to iOS (does nothing on Android as it always silently registers)
* Request for Direct-To-History push notification authorization
*
* For more information: https://documentation.onesignal.com/docs/ios-customizations#provisional-push-notifications
*
* @param {(response:boolean) => void} handler
* @returns void
*/
static registerForProvisionalAuthorization(
handler: (response: boolean) => void,
): void {
/** Indicates whether privacy consent has been granted. */
export function getPrivacyConsent(): Promise<boolean> {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
return Promise.reject(new Error('OneSignal native module not loaded'));
}
if (Platform.OS === 'ios') {
isValidCallback(handler);
RNOneSignal.registerForProvisionalAuthorization(handler);
} else {
console.log(
'registerForProvisionalAuthorization: this function is not supported on Android',
);
}
return RNOneSignal.getPrivacyConsent();
}
/**
* Disable the push notification subscription to OneSignal.
* @param {boolean} disable
* @returns void
* If your application is set to require the user's privacy consent, you can provide this consent using this method.
* Indicates whether privacy consent has been granted. This field is only relevant when the application has opted
* into data privacy protections.
*/
static disablePush(disable: boolean): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
export function setPrivacyConsent(granted: boolean) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.disablePush(disable);
RNOneSignal.setPrivacyConsent(granted);
}
/**
* Android Only. If notifications are disabled for your application, unsubscribe the user from OneSignal.
* @param {boolean} unsubscribe
* @returns void
*/
static unsubscribeWhenNotificationsAreDisabled(unsubscribe: boolean): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
/** This method can be used to set if launch URLs should be opened in safari or within the application. */
export function setLaunchURLsInApp(isEnabled: boolean) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
if (Platform.OS === 'android') {
RNOneSignal.unsubscribeWhenNotificationsAreDisabled(unsubscribe);
if (Platform.OS === 'ios') {
RNOneSignal.setLaunchURLsInApp(isEnabled);
} else {
console.log(
'unsubscribeWhenNotificationsAreDisabled: this function is not supported on iOS',
'setLaunchURLsInApp: this function is not supported on Android',
);
}
}
/* L I V E A C T I V I T Y */
/**
* Associates a temporary push token with an Activity ID on the OneSignal server.
* @param {string} activityId
* @param {string} token
* @param {Function} handler
* @returns void
*/
static enterLiveActivity(
/** Associates a temporary push token with an Activity ID on the OneSignal server. */
export function enterLiveActivity(
activityId: string,
token: string,
handler?: Function,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
if (!handler) {
handler = function () {};
handler = () => {};
}

@@ -354,13 +163,8 @@

* Deletes activityId associated temporary push token on the OneSignal server.
* @param {string} activityId
* @param {Function} handler
* @returns void
*/
static exitLiveActivity(activityId: string, handler?: Function): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
export function exitLiveActivity(activityId: string, handler?: Function) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
if (!handler) {
handler = function () {};
handler = () => {};
}

@@ -374,747 +178,572 @@

/* L O C A T I O N */
/** Clears all handlers and observers. */
export function clearHandlers() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* True if the application has location share activated, false otherwise
* @returns Promise<boolean>
*/
static isLocationShared(): Promise<boolean> {
// must return a promise
if (!isNativeModuleLoaded(RNOneSignal)) {
return Promise.resolve(false);
}
return RNOneSignal.isLocationShared();
eventManager.clearHandlers();
}
/**
* Disable or enable location collection (defaults to enabled if your app has location permission).
* @param {boolean} shared
* @returns void
*/
static setLocationShared(shared: boolean): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
export namespace Debug {
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
* @param {LogLevel} nsLogLevel - Sets the logging level to print to the Android LogCat log or Xcode log.
*/
export function setLogLevel(nsLogLevel: LogLevel) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.setLogLevel(nsLogLevel);
}
RNOneSignal.setLocationShared(shared);
}
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
* @param {LogLevel} visualLogLevel - Sets the logging level to show as alert dialogs.
*/
export function setAlertLevel(visualLogLevel: LogLevel) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Prompts the user for location permissions to allow geotagging from the OneSignal dashboard.
* @returns void
*/
static promptLocation(): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.setAlertLevel(visualLogLevel);
}
//Supported in both iOS & Android
RNOneSignal.promptLocation();
}
/* D E V I C E I N F O */
export namespace User {
export namespace PushSubscription {
/** Add a callback that fires when the OneSignal subscription state changes. */
export function addChangeHandler(
handler: (event: PushSubscription) => void,
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Gets the device state.
* This method returns a "snapshot" of the device state for when it was called.
* @returns Promise<DeviceState | null>
*/
static async getDeviceState(): Promise<DeviceState | null> {
if (!isNativeModuleLoaded(RNOneSignal)) {
return Promise.resolve(null);
}
const deviceState = await RNOneSignal.getDeviceState();
isValidCallback(handler);
RNOneSignal.addPushSubscriptionChangeHandler();
eventManager.addEventHandler<PushSubscription>(
SUBSCRIPTION_CHANGED,
handler,
);
}
if (Platform.OS === 'android') {
deviceState.hasNotificationPermission =
deviceState.areNotificationsEnabled;
delete deviceState.areNotificationsEnabled;
}
/** Clears current subscription observers. */
export function removeChangeHandler() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
return deviceState;
}
RNOneSignal.removePushSubscriptionChangeHandler();
eventManager.clearEventHandler(SUBSCRIPTION_CHANGED);
}
/**
* Allows you to set the app defined language with the OneSignal SDK.
* @param {string} language
* @param {(success:object) => void} onSuccess
* @param {(failure:object) => void} onFailure
* @returns void
*/
static setLanguage(
language: string,
onSuccess?: (success: object) => void,
onFailure?: (failure: object) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
/** The readonly push subscription ID */
export function getPushSubscriptionId(): string {
if (!isNativeModuleLoaded(RNOneSignal)) {
return '';
}
if (!onSuccess) {
onSuccess = function () {};
}
return pushSubscription.id;
}
if (!onFailure) {
onFailure = function () {};
}
RNOneSignal.setLanguage(language, onSuccess, onFailure);
}
/** The readonly push subscription token */
export function getPushSubscriptionToken(): string {
if (!isNativeModuleLoaded(RNOneSignal)) {
return '';
}
/* T A G S */
return pushSubscription.token;
}
/**
* Tag a user based on an app event of your choosing so they can be targeted later via segments.
* @param {string} key
* @param {string} value
* @returns void
*/
static sendTag(key: string, value: string): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
/**
* Gets a boolean value indicating whether the current user is opted in to push notifications.
* This returns true when the app has notifications permission and optOut is not called.
* Note: Does not take into account the existence of the subscription ID and push token.
* This boolean may return true but push notifications may still not be received by the user.
*/
export function getOptedIn(): boolean {
if (!isNativeModuleLoaded(RNOneSignal)) {
return false;
}
if (!key || (!value && value !== '')) {
console.error('OneSignal: sendTag: must include a key and a value');
}
return pushSubscription.optedIn;
}
RNOneSignal.sendTag(key, value);
}
/** Enable the push notification subscription to OneSignal. */
export function optOut() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Tag a user with multiple tags based on an app event of your choosing so they can be targeted later via segments.
* @param {[key: string]: string} tags
* @returns void
*/
static sendTags(tags: { [key: string]: string }): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
let keys = Object.keys(tags);
RNOneSignal.optOut();
}
if (keys.length === 0) {
console.error(
"OneSignal: sendTags: argument must be of type object of the form { key : 'value' }",
);
/** Disable the push notification subscription to OneSignal. */
export function optIn() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.optIn();
}
}
RNOneSignal.sendTags(tags || {});
}
/** Explicitly set a 2-character language code for the user. */
export function setLanguage(language: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Retrieve a list of tags that have been set on the user from the OneSignal server.
* @param {(tags: {[key: string]: string} | null) => void} handler
* @returns void
*/
static getTags(
handler: (tags: { [key: string]: string } | null) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.setLanguage(language);
}
RNOneSignal.getTags(handler);
}
/**
* Deletes a single tag that was previously set on a user.
* @param {string} key
* @returns void
*/
static deleteTag(key: string): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (typeof key !== 'string') {
console.error(
'OneSignal: deleteTag: key argument must be of type string',
);
}
RNOneSignal.deleteTags([key]);
}
/** Set an alias for the current user. If this alias label already exists on this user, it will be overwritten with the new alias id. */
export function addAlias(label: string, id: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Deletes multiple tags that were previously set on a user.
* @param {string[]} keys
*/
static deleteTags(keys: string[]): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.addAlias(label, id);
}
if (!Array.isArray(keys)) {
console.error('OneSignal: deleteTags: argument must be of array type');
/** Set aliases for the current user. If any alias already exists, it will be overwritten to the new values. */
export function addAliases(aliases: object) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.addAliases(aliases);
}
RNOneSignal.deleteTags(keys);
}
/** Remove an alias from the current user. */
export function removeAlias(label: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/* E M A I L */
/**
* Allows you to set the user's email address with the OneSignal SDK.
* @param {string} email
* @param {string} emailAuthCode
* @param {Function} handler
* @returns void
*/
static setEmail(
email: string,
emailAuthCode?: string | null,
handler?: Function,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.removeAlias(label);
}
if (emailAuthCode === undefined) {
emailAuthCode = null;
}
/** Remove aliases from the current user. */
export function removeAliases(labels: string[]) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
// Android workaround for the current issue of callback fired more than once
if (!handler && Platform.OS === 'ios') {
handler = function () {};
RNOneSignal.removeAliases(labels);
}
RNOneSignal.setEmail(email, emailAuthCode, handler);
}
/** Add a new email subscription to the current user. */
export function addEmail(email: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* If your app implements logout functionality, you can call logoutEmail to dissociate the email from the device.
* @param {Function} handler
*/
static logoutEmail(handler?: Function): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.addEmail(email);
}
// Android workaround for the current issue of callback fired more than once
if (!handler && Platform.OS === 'ios') {
handler = function () {};
/**
* Remove an email subscription from the current user. Returns false if the specified email does not exist on the user within the SDK,
* and no request will be made.
*/
export function removeEmail(email: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.removeEmail(email);
}
RNOneSignal.logoutEmail(handler);
}
/** Add a new SMS subscription to the current user. */
export function addSms(smsNumber: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/* S M S */
/**
* Allows you to set the user's SMS number with the OneSignal SDK.
* @param {string} smsNumber
* @param {string} smsAuthCode
* @param {Function} handler
* @returns void
*/
static setSMSNumber(
smsNumber: string,
smsAuthCode?: string | null,
handler?: Function,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.addSms(smsNumber);
}
if (smsAuthCode === undefined) {
smsAuthCode = null;
}
/**
* Remove an SMS subscription from the current user. Returns false if the specified SMS number does not exist on the user within the SDK,
* and no request will be made.
*/
export function removeSms(smsNumber: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
// Android workaround for the current issue of callback fired more than once
if (!handler && Platform.OS === 'ios') {
handler = function () {};
RNOneSignal.removeSms(smsNumber);
}
RNOneSignal.setSMSNumber(smsNumber, smsAuthCode, handler);
}
/**
* Add a tag for the current user. Tags are key:value pairs used as building blocks for targeting specific users and/or personalizing
* messages. If the tag key already exists, it will be replaced with the value provided here.
*/
export function addTag(key: string, value: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* If your app implements logout functionality, you can call logoutSMSNumber to dissociate the SMS number from the device.
* @param {Function} handler
*/
static logoutSMSNumber(handler?: Function): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (!key || (!value && value !== '')) {
console.error('OneSignal: sendTag: must include a key and a value');
return;
}
// Android workaround for the current issue of callback fired more than once
if (!handler && Platform.OS === 'ios') {
handler = function () {};
RNOneSignal.addTag(key, value);
}
RNOneSignal.logoutSMSNumber(handler);
}
/**
* Add multiple tags for the current user. Tags are key:value pairs used as building blocks for targeting
* specific users and/or personalizing messages. If the tag key already exists, it will be replaced with
* the value provided here.
*/
export function addTags(tags: object) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/* N O T I F I C A T I O N S */
if (!tags || Object.keys(tags).length === 0) {
console.error(
'OneSignal: addTags: argument must be of type object of the form { key : "value" }',
);
return;
}
/**
* Send a notification
* @param {string} notificationObjectString - JSON string payload (see REST API reference)
* @param {(success:object) => void} onSuccess
* @param {(failure:object) => void} onFailure
* @returns void
*/
static postNotification(
notificationObjectString: string,
onSuccess?: (success: object) => void,
onFailure?: (failure: object) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.addTags(tags);
}
if (!onSuccess) {
onSuccess = function () {};
}
/** Remove the data tag with the provided key from the current user. */
export function removeTag(key: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
if (!onFailure) {
onFailure = function () {};
if (typeof key !== 'string') {
console.error(
'OneSignal: removeTag: key argument must be of type string',
);
return;
}
RNOneSignal.removeTags([key]);
}
RNOneSignal.postNotification(
notificationObjectString,
onSuccess,
onFailure,
);
}
/** Remove multiple tags with the provided keys from the current user. */
export function removeTags(keys: string[]) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Android Only. iOS provides a standard way to clear notifications by clearing badge count.
* @returns void
*/
static clearOneSignalNotifications(): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
if (!Array.isArray(keys)) {
console.error('OneSignal: removeTags: argument must be of array type');
return;
}
if (Platform.OS === 'android') {
RNOneSignal.clearOneSignalNotifications();
} else {
console.log(
'clearOneSignalNotifications: this function is not supported on iOS',
);
RNOneSignal.removeTags(keys);
}
}
/**
* Android Only.
* Removes a single OneSignal notification based on its Android notification integer id.
* @param {number} id - notification id to cancel
* @returns void
*/
static removeNotification(id: number): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
export namespace Notifications {
/**
* Whether this app has push notification permission. Returns true if the user has accepted permissions,
* or if the app has ephemeral or provisional permission.
*/
export function hasPermission(): boolean {
return notificationPermission;
}
if (Platform.OS === 'android') {
RNOneSignal.removeNotification(id);
} else {
console.log('removeNotification: this function is not supported on iOS');
}
}
/**
* Prompt the user for permission to receive push notifications. This will display the native system prompt to request push
* notification permission. Use the fallbackToSettings parameter to prompt to open the settings app if a user has already
* declined push permissions.
*/
export function requestPermission(
fallbackToSettings: boolean,
): Promise<boolean> {
if (!isNativeModuleLoaded(RNOneSignal)) {
return Promise.reject(new Error('OneSignal native module not loaded'));
}
/**
* Android Only.
* Removes all OneSignal notifications based on its Android notification group Id.
* @param {string} id - notification group id to cancel
* @returns void
*/
static removeGroupedNotifications(id: string): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
return RNOneSignal.requestNotificationPermission(fallbackToSettings);
}
if (Platform.OS === 'android') {
RNOneSignal.removeGroupedNotifications(id);
} else {
console.log(
'removeGroupedNotifications: this function is not supported on iOS',
);
}
}
/**
* Whether attempting to request notification permission will show a prompt. Returns true if the device has not been prompted for push
* notification permission already.
*/
export function canRequestPermission(): Promise<boolean> {
if (!isNativeModuleLoaded(RNOneSignal)) {
return Promise.reject(new Error('OneSignal native module not loaded'));
}
/**
* This method can be used to set if launch URLs should be opened in safari or within the application.
* @param {boolean} isEnabled
* @returns
*/
static setLaunchURLsInApp(isEnabled: boolean): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
return RNOneSignal.canRequestNotificationPermission();
}
if (Platform.OS === 'ios') {
RNOneSignal.setLaunchURLsInApp(isEnabled);
} else {
console.log(
'setLaunchURLsInApp: this function is not supported on Android',
);
/**
* Instead of having to prompt the user for permission to send them push notifications, your app can request provisional authorization.
* For more information: https://documentation.onesignal.com/docs/ios-customizations#provisional-push-notifications
* @param {(response:{accepted:boolean})=>void} handler
*/
export function registerForProvisionalAuthorization(
handler: (response: boolean) => void,
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
if (Platform.OS === 'ios') {
isValidCallback(handler);
RNOneSignal.registerForProvisionalAuthorization(handler);
} else {
console.log(
'registerForProvisionalAuthorization: this function is not supported on Android',
);
}
}
}
/* E X T E R N A L U S E R I D */
/** Add a callback that fires when the native push permission changes. */
export function addPermissionChangedHandler(
observer: (event: { permission: boolean }) => void,
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Allows you to use your own system's user ID's to send push notifications to your users.
* @param {string} externalId
* @param {string} externalIdAuthCode?
* @param {(results:object) => void} handler?
* @returns void
*/
static setExternalUserId(
externalId: string,
handlerOrAuth?: ((results: object) => void) | string,
handler?: (results: object) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
isValidCallback(observer);
RNOneSignal.addPermissionChangedHandler();
eventManager.addEventHandler<{ permission: boolean }>(
PERMISSION_CHANGED,
observer,
);
}
if (typeof handlerOrAuth === 'function') {
RNOneSignal.setExternalUserId(externalId, null, handlerOrAuth);
return;
}
/** Remove permission observer that have been previously added. */
export function removePermissionChangedHandler() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
if (!handler && Platform.OS === 'ios') {
handler = function () {};
RNOneSignal.removePermissionChangedHandler();
eventManager.clearEventHandler(PERMISSION_CHANGED);
}
RNOneSignal.setExternalUserId(externalId, handlerOrAuth, handler);
}
/** Sets a handler that will run whenever a notification is opened by the user. */
export function setNotificationClickHandler(
handler: (openedEvent: OpenedEvent) => void,
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Removes whatever was set as the current user's external user ID.
* @param {(results:object) => void} handler
* @returns void
*/
static removeExternalUserId(handler?: (results: object) => void): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
isValidCallback(handler);
// Android workaround for the current issue of callback fired more than once
if (handler === undefined && Platform.OS === 'ios') {
handler = function () {};
RNOneSignal.setNotificationClickHandler();
eventManager.setEventHandler<OpenedEvent>(NOTIFICATION_CLICKED, handler);
}
RNOneSignal.removeExternalUserId(handler);
}
/**
* Sets the handler to run before displaying a notification while the app is in focus. Use this handler to read notification
* data and change it or decide if the notification should show or not.
* Note: this runs after the Notification Service Extension which can be used to modify the notification before showing it.
*/
export function setNotificationWillShowInForegroundHandler(
handler: (event: NotificationReceivedEvent) => void,
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/* I N A P P M E S S A G I N G */
isValidCallback(handler);
/**
* Sets an In-App Message click event handler.
* @param {(action:InAppMessageAction) => void} handler
* @returns void
*/
static setInAppMessageClickHandler(
handler: (action: InAppMessageAction) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.setNotificationWillShowInForegroundHandler();
eventManager.setEventHandler<NotificationReceivedEvent>(
NOTIFICATION_WILL_SHOW,
handler,
);
}
isValidCallback(handler);
RNOneSignal.initInAppMessageClickHandlerParams();
RNOneSignal.setInAppMessageClickHandler();
eventManager.setEventHandler<InAppMessageAction>(
IN_APP_MESSAGE_CLICKED,
handler,
);
}
/**
* Sets the In-App Message lifecycle handler object to run on displaying and/or dismissing an In-App Message.
* @param {InAppMessageLifecycleHandlerObject} handlerObject
* @returns void
*/
static setInAppMessageLifecycleHandler(
handlerObject: InAppMessageLifecycleHandlerObject,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
/**
* Removes all OneSignal notifications.
* Android Only. iOS provides a standard way to clear notifications by clearing badge count.
*/
export function clearAll() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
if (handlerObject.onWillDisplayInAppMessage) {
isValidCallback(handlerObject.onWillDisplayInAppMessage);
eventManager.setEventHandler<InAppMessage>(
IN_APP_MESSAGE_WILL_DISPLAY,
handlerObject.onWillDisplayInAppMessage,
);
RNOneSignal.clearAllNotifications();
}
if (handlerObject.onDidDisplayInAppMessage) {
isValidCallback(handlerObject.onDidDisplayInAppMessage);
eventManager.setEventHandler<InAppMessage>(
IN_APP_MESSAGE_DID_DISPLAY,
handlerObject.onDidDisplayInAppMessage,
);
}
if (handlerObject.onWillDismissInAppMessage) {
isValidCallback(handlerObject.onWillDismissInAppMessage);
eventManager.setEventHandler<InAppMessage>(
IN_APP_MESSAGE_WILL_DISMISS,
handlerObject.onWillDismissInAppMessage,
);
}
if (handlerObject.onDidDismissInAppMessage) {
isValidCallback(handlerObject.onDidDismissInAppMessage);
eventManager.setEventHandler<InAppMessage>(
IN_APP_MESSAGE_DID_DISMISS,
handlerObject.onDidDismissInAppMessage,
);
}
RNOneSignal.setInAppMessageLifecycleHandler();
}
/**
* Android Only.
* Removes a single OneSignal notification based on its Android notification integer id.
*/
export function removeNotification(id: number) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Add an In-App Message Trigger.
* @param {string} key
* @param {string | number | boolean} value
* @returns void
*/
static addTrigger(key: string, value: string | number | boolean): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
if (Platform.OS === 'android') {
RNOneSignal.removeNotification(id);
} else {
console.log(
'removeNotification: this function is not supported on iOS',
);
}
}
// value can be assigned to `false` so we cannot just check `!value`
if (!key || value == null) {
console.error('OneSignal: addTrigger: must include a key and a value');
/**
* Android Only.
* Removes all OneSignal notifications based on its Android notification group Id.
* @param {string} id - notification group id to cancel
*/
export function removeGroupedNotifications(id: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
if (Platform.OS === 'android') {
RNOneSignal.removeGroupedNotifications(id);
} else {
console.log(
'removeGroupedNotifications: this function is not supported on iOS',
);
}
}
let trigger: { [key: string]: string | number | boolean } = {};
trigger[key] = value;
RNOneSignal.addTriggers(trigger);
}
/**
* Adds Multiple In-App Message Triggers.
* @param {[key: string]: string | number | boolean} triggers
* @returns void
*/
static addTriggers(triggers: {
[key: string]: string | number | boolean;
}): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
export namespace InAppMessages {
/** Set the in-app message click handler. */
export function setClickHandler(
handler: (action: InAppMessageAction) => void,
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
let keys = Object.keys(triggers);
if (keys.length === 0) {
console.error(
"OneSignal: addTriggers: argument must be an object of the form { key : 'value' }",
isValidCallback(handler);
RNOneSignal.setInAppMessageClickHandler();
eventManager.setEventHandler<InAppMessageAction>(
IN_APP_MESSAGE_CLICKED,
handler,
);
}
RNOneSignal.addTriggers(triggers);
}
/** Set the in-app message lifecycle handler. */
export function setLifecycleHandler(
handlerObject: InAppMessageLifecycleHandlerObject,
) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Removes a list of triggers based on a collection of keys.
* @param {string[]} keys
* @returns void
*/
static removeTriggersForKeys(keys: string[]): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
if (handlerObject.onWillDisplayInAppMessage) {
isValidCallback(handlerObject.onWillDisplayInAppMessage);
eventManager.setEventHandler<InAppMessage>(
IN_APP_MESSAGE_WILL_DISPLAY,
handlerObject.onWillDisplayInAppMessage,
);
}
if (handlerObject.onDidDisplayInAppMessage) {
isValidCallback(handlerObject.onDidDisplayInAppMessage);
eventManager.setEventHandler<InAppMessage>(
IN_APP_MESSAGE_DID_DISPLAY,
handlerObject.onDidDisplayInAppMessage,
);
}
if (handlerObject.onWillDismissInAppMessage) {
isValidCallback(handlerObject.onWillDismissInAppMessage);
eventManager.setEventHandler<InAppMessage>(
IN_APP_MESSAGE_WILL_DISMISS,
handlerObject.onWillDismissInAppMessage,
);
}
if (handlerObject.onDidDismissInAppMessage) {
isValidCallback(handlerObject.onDidDismissInAppMessage);
eventManager.setEventHandler<InAppMessage>(
IN_APP_MESSAGE_DID_DISMISS,
handlerObject.onDidDismissInAppMessage,
);
}
RNOneSignal.setInAppMessagesLifecycleHandler();
}
RNOneSignal.removeTriggersForKeys(keys);
}
/**
* Add a trigger for the current user. Triggers are currently explicitly used to determine whether a specific IAM should be
* displayed to the user.
*/
export function addTrigger(key: string, value: string | number | boolean) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Removes a list of triggers based on a key.
* @param {string} key
* @returns void
*/
static removeTriggerForKey(key: string): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.removeTriggerForKey(key);
}
// value can be assigned to `false` so we cannot just check `!value`
if (!key || value == null) {
console.error('OneSignal: addTrigger: must include a key and a value');
}
/**
* Gets a trigger value for a provided trigger key.
* @param {string} key
* @returns Promise<string | number | boolean | null>
*/
static getTriggerValueForKey(
key: string,
): Promise<string | number | boolean | null> {
// must return a promise
if (!isNativeModuleLoaded(RNOneSignal)) {
return Promise.resolve(null);
let trigger: { [key: string]: string | number | boolean } = {};
trigger[key] = value;
RNOneSignal.addTriggers(trigger);
}
return RNOneSignal.getTriggerValueForKey(key);
}
/**
* Pause & unpause In-App Messages
* @param {boolean} pause
* @returns void
*/
static pauseInAppMessages(pause: boolean): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
}
RNOneSignal.pauseInAppMessages(pause);
}
/**
* Add multiple triggers for the current user. Triggers are currently explicitly used to determine whether a specific IAM should
* be displayed to the user.
*/
export function addTriggers(triggers: {
[key: string]: string | number | boolean;
}) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/* O U T C O M E S */
let keys = Object.keys(triggers);
/**
* Increases the "Count" of this Outcome by 1 and will be counted each time sent.
* @param {string} name
* @param {(event:OutcomeEvent) => void} handler
* @returns void
*/
static sendOutcome(
name: string,
handler?: (event: OutcomeEvent) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
if (keys.length === 0) {
console.error(
"OneSignal: addTriggers: argument must be an object of the form { key : 'value' }",
);
}
RNOneSignal.addTriggers(triggers);
}
if (!handler) {
handler = function () {};
/** Remove the trigger with the provided key from the current user. */
export function removeTrigger(key: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.removeTrigger(key);
}
RNOneSignal.sendOutcome(name, handler);
}
/** Remove multiple triggers from the current user. */
export function removeTriggers(keys: string[]) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Increases "Count" by 1 only once. This can only be attributed to a single notification.
* @param {string} name
* @param {(event:OutcomeEvent) => void} handler
* @returns void
*/
static sendUniqueOutcome(
name: string,
handler?: (event: OutcomeEvent) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.removeTriggers(keys);
}
if (!handler) {
handler = function () {};
/** Clear all triggers from the current user. */
export function clearTriggers() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.clearTriggers();
}
RNOneSignal.sendUniqueOutcome(name, handler);
}
/**
* Set whether in-app messaging is currently paused.
* When set to true no IAM will be presented to the user regardless of whether they qualify for them.
* When set to 'false` any IAMs the user qualifies for will be presented to the user at the appropriate time.
*/
export function setPaused(pause: boolean) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Increases the "Count" of this Outcome by 1 and the "Sum" by the value. Will be counted each time sent.
* If the method is called outside of an attribution window, it will be unattributed until a new session occurs.
* @param {string} name
* @param {string|number} value
* @param {(event:OutcomeEvent) => void} handler
* @returns void
*/
static sendOutcomeWithValue(
name: string,
value: string | number,
handler?: (event: OutcomeEvent) => void,
): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.paused(pause);
}
if (!handler) {
handler = function () {};
/** Whether in-app messaging is currently paused. */
export function getPaused(): Promise<boolean> {
if (!isNativeModuleLoaded(RNOneSignal)) {
return Promise.reject(new Error('OneSignal native module not loaded'));
}
return RNOneSignal.getPaused();
}
RNOneSignal.sendOutcomeWithValue(name, Number(value), handler);
}
/* P R I V A C Y C O N S E N T */
export namespace Location {
/** Prompts the user for location permissions to allow geotagging from the OneSignal dashboard. */
export function requestPermission() {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Did the user provide privacy consent for GDPR purposes.
* @returns Promise<boolean>
*/
static userProvidedPrivacyConsent(): Promise<boolean> {
if (!isNativeModuleLoaded(RNOneSignal)) {
return Promise.resolve(false);
RNOneSignal.requestLocationPermission();
}
//returns a promise
return RNOneSignal.userProvidedPrivacyConsent();
}
/** Disable or enable location collection (defaults to enabled if your app has location permission). */
export function setShared(shared: boolean) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* True if the application requires user privacy consent, false otherwise
* @returns Promise<boolean>
*/
static requiresUserPrivacyConsent(): Promise<boolean> {
if (!isNativeModuleLoaded(RNOneSignal)) {
return Promise.resolve(false);
RNOneSignal.setLocationShared(shared);
}
//returns a promise
return RNOneSignal.requiresUserPrivacyConsent();
}
/**
* Checks if location collection is enabled or disabled.
* @param {(value: boolean) => void} handler
*/
export function isShared(): Promise<boolean> {
if (!isNativeModuleLoaded(RNOneSignal)) {
return Promise.reject(new Error('OneSignal native module not loaded'));
}
/**
* For GDPR users, your application should call this method before setting the App ID.
* @param {boolean} required
* @returns void
*/
static setRequiresUserPrivacyConsent(required: boolean): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
return RNOneSignal.isLocationShared();
}
RNOneSignal.setRequiresUserPrivacyConsent(required);
}
/**
* If your application is set to require the user's privacy consent, you can provide this consent using this method.
* @param {boolean} granted
* @returns void
*/
static provideUserConsent(granted: boolean): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
export namespace Session {
/** Increases the "Count" of this Outcome by 1 and will be counted each time sent. */
export function addOutcome(name: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
RNOneSignal.addOutcome(name);
}
RNOneSignal.provideUserConsent(granted);
}
/** Increases "Count" by 1 only once. This can only be attributed to a single notification. */
export function addUniqueOutcome(name: string) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/* O T H E R F U N C T I O N S */
/**
* Enable logging to help debug if you run into an issue setting up OneSignal.
* @param {LogLevel} nsLogLevel - Sets the logging level to print to the Android LogCat log or Xcode log.
* @param {LogLevel} visualLogLevel - Sets the logging level to show as alert dialogs.
* @returns void
*/
static setLogLevel(nsLogLevel: LogLevel, visualLogLevel: LogLevel): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.addUniqueOutcome(name);
}
RNOneSignal.setLogLevel(nsLogLevel, visualLogLevel);
}
/**
* Increases the "Count" of this Outcome by 1 and the "Sum" by the value. Will be counted each time sent.
* If the method is called outside of an attribution window, it will be unattributed until a new session occurs.
*/
export function addOutcomeWithValue(name: string, value: string | number) {
if (!isNativeModuleLoaded(RNOneSignal)) return;
/**
* Clears all handlers and observers.
* @returns void
*/
static clearHandlers(): void {
if (!isNativeModuleLoaded(RNOneSignal)) {
return;
RNOneSignal.addOutcomeWithValue(name, Number(value));
}
eventManager.clearHandlers();
}
}
/* Export all public models */
export {
ChangeEvent,
PermissionChange,
SubscriptionChange,
EmailSubscriptionChange,
SMSSubscriptionChange,
NotificationReceivedEvent,

@@ -1126,3 +755,2 @@ OpenedEvent,

OutcomeEvent,
DeviceState,
};

@@ -1135,5 +763,2 @@

} from './models/NotificationEvents';
export {
IosPermissionStatus,
ObserverChangeEvent,
} from './models/Subscription';
export { IosPermissionStatus } from './models/Subscription';
// 0 = NotDetermined, 1 = Denied, 2 = Authorized, 3 = Provisional, 4 = Ephemeral
export type IosPermissionStatus = 0 | 1 | 2 | 3 | 4;
/* D E V I C E */
export interface DeviceState {
userId: string;
pushToken: string;
emailUserId: string;
emailAddress: string;
smsUserId: string;
smsNumber: string;
isSubscribed: boolean;
isPushDisabled: boolean;
isEmailSubscribed: boolean;
isSMSSubscribed: boolean;
hasNotificationPermission?: boolean; // is areNotificationsEnabled on android
notificationPermissionStatus?: IosPermissionStatus; // ios only
// areNotificationsEnabled (android) not included since it is converted to hasNotificationPermission in bridge
export interface PushSubscription {
id: string;
token: string;
optedIn: boolean;
}
/* O B S E R V E R C H A N G E E V E N T S */
export interface ChangeEvent<ObserverChangeEvent> {
from: ObserverChangeEvent;
to: ObserverChangeEvent;
}
export type ObserverChangeEvent =
| PermissionChange
| SubscriptionChange
| EmailSubscriptionChange
| SMSSubscriptionChange;
export interface PermissionChange {
status?: IosPermissionStatus; // ios
hasPrompted?: boolean; // ios
provisional?: boolean; // ios
areNotificationsEnabled?: boolean; // android
}
export interface SubscriptionChange {
userId?: string;
pushToken?: string;
isSubscribed: boolean;
isPushDisabled: boolean;
}
export interface EmailSubscriptionChange {
emailAddress?: string;
emailUserId?: string;
isEmailSubscribed: boolean;
}
export interface SMSSubscriptionChange {
smsNumber?: string;
smsUserId?: string;
isSMSSubscribed: boolean;
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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