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

react-onesignal

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-onesignal

React OneSignal Module: Make it easy to integrate OneSignal with your React App!


Version published
Weekly downloads
29K
increased by1.07%
Maintainers
9
Weekly downloads
 
Created



Showing web push notifications from Chrome, Safari, and Firefox

This is a JavaScript module that can be used to easily include OneSignal code in a website or app in practically any JS front-end codebase (not limited to React).

This is a JavaScript module that can be used to easily include OneSignal code in a website or app that uses React for its front-end codebase.

OneSignal is the world's leader for Mobile Push Notifications, Web Push, and In-App Messaging. It is trusted by 2 million+ businesses to send 9 billion Push Notifications per day.

You can find more information on OneSignal here.

Migration Guides

Versions 2.0 and 3.0 were recently released and include breaking changes. See the Migration Guide to update your implementation.

ATTENTION: v3 is currently in Beta 🚧 and includes a fundamental shift to the OneSignal subscriber ("player") model. Learn more here.

Contents


Install

You can use yarn or npm.

Yarn

yarn add react-onesignal

npm

npm install --save react-onesignal

Usage

Initialize OneSignal with your appId via the options parameter:

import OneSignal from 'react-onesignal';

OneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' });

The init function returns a promise that resolves when OneSignal is loaded.

Examples

await OneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' });
// do other stuff

const [initialized, setInitialized] = useState(false);
OneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' }).then(() => {
  setInitialized(true);
  OneSignal.Slidedown.promptPush();
  // do other stuff
})

Init Options

You can pass other options to the init function. Use these options to configure personalized prompt options, auto-resubscribe, and more.

Expand to see more options
Property NameTypeDescription
appIdstringThe ID of your OneSignal app.
autoRegisterboolean (optional)Whether or not to automatically register the user.
autoResubscribeboolean (optional)Whether or not to automatically resubscribe the user.
pathstring (optional)The path to the OneSignal service worker file.
serviceWorkerPathstring (optional)The path to the OneSignal service worker script.
serviceWorkerUpdaterPathstring (optional)The path to the OneSignal service worker updater script.
subdomainNamestring (optional)The subdomain of your OneSignal app.
allowLocalhostAsSecureOriginboolean (optional)Whether or not to allow localhost as a secure origin.
requiresUserPrivacyConsentboolean (optional)Whether or not the user's consent is required.
persistNotificationboolean (optional)Whether or not notifications should persist.
notificationClickHandlerMatchstring (optional)The URL match pattern for notification clicks.
notificationClickHandlerActionstring (optional)The action to perform when a notification is clicked.
welcomeNotificationobject (optional)The welcome notification configuration.
notifyButtonobject (optional)The notify button configuration.
promptOptionsobject (optional)Additional options for the subscription prompt.
webhooksobject (optional)The webhook configuration.
[key: string]anyAdditional properties can be added as needed.

Service Worker Params You can customize the location and filenames of service worker assets. You are also able to specify the specific scope that your service worker should control. You can read more here.

In this distribution, you can specify the parameters via the following:

FieldDetails
serviceWorkerParamUse to specify the scope, or the path the service worker has control of. Example: { scope: "/js/push/onesignal/" }
serviceWorkerPathThe path to the service worker file.

Service Worker File

If you haven't done so already, you will need to add the OneSignal Service Worker file to your site (learn more).

The OneSignal SDK file must be publicly accessible. You can put them in your top-level root or a subdirectory. However, if you are placing the file not on top-level root make sure to specify the path via the service worker params in the init options (see section above).

Tip: Visit https://yoursite.com/OneSignalSDKWorker.js in the address bar to make sure the files are being served successfully.


Typescript

This package includes Typescript support.

interface IOneSignalOneSignal {
	Slidedown: IOneSignalSlidedown;
	Notifications: IOneSignalNotifications;
	Session: IOneSignalSession;
	User: IOneSignalUser;
	Debug: IOneSignalDebug;
	login(externalId: string, jwtToken?: string): Promise<void>;
	logout(): Promise<void>;
	init(options: IInitObject): Promise<void>;
	setConsentGiven(consent: boolean): Promise<void>;
	setConsentRequired(requiresConsent: boolean): Promise<void>;
}

OneSignal API

See the official OneSignal WebSDK reference for information on all available SDK functions.


Advanced Usage

Events and Event Listeners

Use listeners to react to OneSignal-related events:

Notifications Namespace

Event NameCallback Argument Type
'click'NotificationClickResult
'foregroundWillDisplay'NotificationForegroundWillDisplayEvent
'dismiss'OSNotificationDataPayload
'permissionChange'boolean
'permissionPromptDisplay'void
Expand to see associated types
NotificationClickResult
PropertyDescription
actionIdA string representing the action ID associated with the click event
urlA string representing the URL associated with the click event
NotificationForegroundWillDisplayEvent
PropertyDescription
notificationAn OSNotification type object
OSNotification
PropertyDescription
idOptional string representing the unique identifier of the notification.
titleOptional string representing the title of the notification.
bodyOptional string representing the body of the notification.
dataOptional data object associated with the notification.
urlOptional string representing the URL to be opened when the notification is clicked.
iconOptional string representing the URL of the icon to be displayed with the notification.
imageOptional string representing the URL of the image to be displayed with the notification.
tagOptional string representing a unique identifier for a group of notifications.
requireInteractionOptional boolean indicating whether the notification requires user interaction or not.
renotifyOptional boolean indicating whether the notification should be replaced or not, if a notification with the same tag is already displayed.
actionsOptional array of NotificationActionButton objects representing the action buttons associated with the notification.
NotificationActionButton
PropertyDescription
actionA string representing the action associated with the button.
titleA string representing the title of the button.
iconOptional string representing the URL of the icon to be displayed with the button.
urlOptional string representing the URL to be opened when the button is clicked.
OSNotificationDataPayload
PropertyDescription
idA string representing the unique identifier of the notification data payload.
contentA string representing the content of the notification data payload.
headingOptional string representing the heading of the notification data payload.
urlOptional string representing the URL to be opened when the notification data payload is clicked.
dataOptional object containing additional data associated with the notification data payload.
rrOptional string with value 'y' or 'n' representing whether or not the notification has Confirmed Delivery.
iconOptional string representing the URL of the icon to be displayed with the notification data payload.
imageOptional string representing the URL of the image to be displayed with the notification data payload.
tagOptional string representing a unique identifier for a group of notification data payloads.
badgeOptional string representing the URL of the badge to be displayed with the notification data payload.
vibrateOptional array of numbers representing the vibration pattern of the notification data payload.
buttonsOptional array of NotificationButtonData objects representing the button data associated with the notification data payload.
NotificationButtonData
PropertyDescription
urlA string representing the URL to be opened when the button is clicked.
idA string representing the ID of the action.
actionA string representing the type of the action (inherited from NotificationAction).
titleA string representing the title of the action button (inherited from NotificationAction).
iconOptional string representing the URL of the icon to be displayed with the action button.

Slidedown Namespace

Event NameCallback Argument Type
'slidedownShown'boolean

Push Subscription Namespace

Event NameCallback Argument Type
'change'boolean

Example

OneSignal.Notifications.addEventListener('click', (result) => {
  console.log("The notification was clicked!", result);
});

See the OneSignal WebSDK Reference for all available event listeners.

Troubleshooting

window.OneSignal already defined as 'object'!

You will get this error if you initialize twice. Make sure you are only initializing one time. When wrapped with React.StrictMode, your app might be rendering twice.

Example App

This repo includes an example React application implementing OneSignal. It was created using create-react-app. The app uses this repository's root level directory as the react-onesignal package and will bundle any changes on every run.


🤝 Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page.

Show your support

Give a ⭐️ if this project helped you!

OneSignal

Discord

Reach out to us via our Discord server!

📝 License

Copyright © 2023 OneSignal.
This project is Modified MIT licensed.

Thanks

Special thanks to pedro-lb and others for work on the project this package is based on.

Enjoy!

FAQs

Package last updated on 16 May 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts