Giter Site home page Giter Site logo

onesignal / react-onesignal Goto Github PK

View Code? Open in Web Editor NEW
74.0 32.0 24.0 680 KB

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

License: Other

JavaScript 5.95% TypeScript 85.45% HTML 5.58% CSS 3.02%
react email push-notifications in-app-messaging sms typescript notifications

react-onesignal's Introduction

Welcome to react-onesignal ๐Ÿ‘‹

Version Documentation Maintenance Twitter: onesignal

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).

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 3.0 were recently released and include breaking changes. See the Migration Guide to update your implementation.

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 Name Type Description
appId string The ID of your OneSignal app.
autoRegister boolean (optional) Whether or not to automatically register the user.
autoResubscribe boolean (optional) Whether or not to automatically resubscribe the user.
path string (optional) The path to the OneSignal service worker file.
serviceWorkerPath string (optional) The path to the OneSignal service worker script.
serviceWorkerUpdaterPath string (optional) The path to the OneSignal service worker updater script.
subdomainName string (optional) The subdomain of your OneSignal app.
allowLocalhostAsSecureOrigin boolean (optional) Whether or not to allow localhost as a secure origin.
requiresUserPrivacyConsent boolean (optional) Whether or not the user's consent is required.
persistNotification boolean (optional) Whether or not notifications should persist.
notificationClickHandlerMatch string (optional) The URL match pattern for notification clicks.
notificationClickHandlerAction string (optional) The action to perform when a notification is clicked.
welcomeNotification object (optional) The welcome notification configuration.
notifyButton object (optional) The notify button configuration.
promptOptions object (optional) Additional options for the subscription prompt.
webhooks object (optional) The webhook configuration.
[key: string] any Additional 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:

Field Details
serviceWorkerParam Use to specify the scope, or the path the service worker has control of. Example: { scope: "/js/push/onesignal/" }
serviceWorkerPath The 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 Name Callback Argument Type
'click' NotificationClickEvent
'foregroundWillDisplay' NotificationForegroundWillDisplayEvent
'dismiss' NotificationDismissEvent
'permissionChange' boolean
'permissionPromptDisplay' void

Slidedown Namespace

Event Name Callback Argument Type
'slidedownShown' boolean

Push Subscription Namespace

Event Name Callback Argument Type
'change' boolean

Example

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

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!

react-onesignal's People

Contributors

david-melo avatar dependabot[bot] avatar emawby avatar jkasten2 avatar jmadler avatar kesheshyan avatar matiyeu avatar pedro-lb avatar rgomezp avatar rodolfosilva avatar slothluvchunk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-onesignal's Issues

[question]: Why is Init async, and shouldnt the window["onesignal"] queue get initialized earlier?

How can we help?

Init doesnt look like it needs to be async. It would be nice if it wasnt - most 3rd party trackers arent.
Also, the window["OneSignal"] property seems to only be instantiated inside of the handleOnLoad method (which is called after the script is loaded). Shouldnt the property and queue be initialized immediately during init/module import vs when the script asynchronously returns?

Thank you!

My player id is unsubscribe when refresh (F5) my app

Hi, I have a problem, maybe my implementation is wrong, but I want your feedback, I've tried to implement onesignal on my reactjs web app (it's not react native).

I tried 3 differents aproachs:
1.- Following the oficial onesignal web push sdk documentation.
2.- This aproach.
3.- Using this aproach https://dev.to/devpato/push-notifications-in-reactjs-with-onesignal-5bon

All of them I've completed successfully, but all have a strange behavior on my reactjs web app.

When my app get the notifications permissions for first time and I accept it, it doesn't show the welcome notification and if I send a notification from my onesignal dashboard it doesn't show.

If I refresh (F5) my app two times and send another notification, it works and show correctly. But if for any reason I refresh again my app, the notifications don't work anymore and in my onesignal dashboard shows that my player id is unsubscribe.

Somebody has the same issue? or what could be wrong in my app? Thanks.

[Bug]: setExternalUserId never resolve

What happened?

  return OneSignal.setExternalUserId(userId).then(res => {
    console.log('setOneSignalExternalUserId never reach');
  }).catch(err => {
    console.log('setOneSignalExternalUserId never reach');
  });

Steps to reproduce?

1. install 'react-onesignal'
2. write code above

What did you expect to happen?

I expect the "setExternalUserId" function to return a Promise that will call "resolve" or "reject" after a time.

Relevant log output

No response

new Audio.play() in event listener 'notificationDisplay' returning not defined

I've done all setup stuff in my react component, receiving notification works fine, the problem is that I need to play a sound when a notification arrives.

My implementations is as follow:
image

The sound.play() function works in a button onclick() and calling it in the component (OrderContainer), but when calling it on callback from the listener it returns an error 'yc is not defined'. I know that some browsers block the autoplay (without user interaction) for media, if is that the case, the feedback is not so clear.

Am I doing something wrong?
I appreciate it if someone can help with this
tks

[Typescript]: Event listeners type signature issue after 2.0.3 release

Hello. When 2.0.3 was released, the listener functions type signature was changed from Function to () => void.
With the new signature, it means that these functions will not receive any arguments. You can see this change here:

https://github.com/OneSignal/react-onesignal/pull/59/files#diff-dcdc3e0b3362edb8fec2a51d3fa51f8fb8af8f70247e06d9887fa934834c9122L107-R126

Now my question is, how are we going to get those values that we were expecting for those events?

For example:

OneSignal.on('subscriptionChange', function(isSubscribed) {
  console.log("The user's subscription state is now:", isSubscribed);
});

This code can't be compiled by typescript. Thanks

OneSignal Initialize Error

So i initialize my onesignal via this, i rechecked my onesignal app id 3,4 times.
import OneSignal from 'react-onesignal';
OneSignal.initialize('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', {
requiresUserPrivacyConsent: true,
notifyButton: {
enable: true,
},
allowLocalhostAsSecureOrigin: true,
subdomainName: 'xxxxxx-xxx',
});

as this is the code snippet provided by my onesignal app so i added these options. But when i try to run my app. Onesignal initializing failed with this error. I'm trying to send notification to my localhost so i have setup my local host correctly as well. With local testing turned on in my site setup of one signal.
Screenshot 2020-09-01 at 11 20 21 AM

Screenshot 2020-09-01 at 11 18 57 AM

logoutEmail() should probably return a promise

Right now it returns void, but clearly there's a network request happening. Chrome is showing me an uncaught exception when there's an error with the call. It would be nice to be able to catch this in my own code.

CleanShot 2021-11-09 at 13 56 22

New Feature Discussion: Event Listeners

Hello, I already made a pull request to add a feature I needed and now I'm facing another need but I'm not sure how we could go about this. OneSignal provides several event listeners that are registered within the PUSH function.

OneSignal.push(function() {
  // Occurs when the user's subscription changes to a new value.
  OneSignal.on('subscriptionChange', function (isSubscribed) {
    console.log("The user's subscription state is now:", isSubscribed);
  });
});

It would be nice if when initializing react-onesignal we could pass in some functions to attach to those listeners. Since react-onesignal just prints out a string for initializing OneSignal, I'm not even sure this would be possible.

Unable to set up oneSignal with React Native Web

I am trying to build a cross platform app ios/android/web using react native. I will be using react native web to build for web. I have followed the setup guide from the documentation, but I was not successful.
I have added the following to my root App component:

useEffect(() => {
        console.log("inisde use effect");
        OneSignalReact.init({ appId: "4ffe42fb-8990-411d-8c23-34f9f393b149" })
            .then(() => console.log("one signal initted"))
            .catch((err) => console.log(err));

        console.log("after use effect");
    }, []);

I have the service worker file "OneSignalSDKWorker.js" in the root of my project, and setup the application on OneSignal for local testing and ran the local server for react native web.

I received the popup asking for the subscription to notification, but when I press subscribe, the service worker fail to load and I get an error.

The script has an unsupported MIME type ('text/html')
[Service Worker Installation] Installing service worker failed SecurityError: Failed to register a ServiceWorker for scope ('http://localhost:19006/') with script ('http://localhost:19006/OneSignalSDKWorker.js?appId=4ffe42fb-8990-411d-8c23-34f9f393b149?sdkVersion=151513'): The script has an unsupported MIME type ('text/html').

Is OneSignal supposed to work with React Native web or what can i do?

[Bug]: Initilization on Firefox doesn't work.

What happened?

Works perfectly on Chrome, but on Firefox, the app using the package is not working. It doesn't give any errors/warnings so it is a bit difficult to know where the issue could be coming from.

One thing I noticed though is that, in Chrome, the indexedDb is automatically created once initialized, but on Firefox, you won't see any relevant database.

Not sure though if this only happens in local development.

Steps to reproduce?

1. Install `react-onesignal`.
2. Run app initializing the SDK.
3. Test on Chrome (to verify it works, and it did - even sent messages from the dashboard).
4. Test on Firefox (doesn't work - not even registered on the Subscribed page in dashboard).

What did you expect to happen?

Should work smoothly like on Chrome. Should have been initialized as intended.

Relevant log output

When you execute OneSignal.isPushNotificationsSupported(); - it returns false.
Firefox v108.0.1
MacOS v12.5.1

Either blocked by client or incorrect use of the react hook

Hi,

So what is the "best practice" in using the react-onesignal module? I see people trying to initialize (here or here and on stackoverflow) the library, but no luck with ordinary ways. Is it expected to use something like <Helmet> or initialize in another way?

If one follows instructions on the documentation, it throws an error:

oneSignal.ts:150 GET https://cdn.onesignal.com/sdks/OneSignalSDK.js
net::ERR_BLOCKED_BY_CLIENT

Can you please elaborate what is the minimal "correct" way of initialization?

Sorry, check with the site admin for error: EACCES : when deploying to production

Hello, I don't know if it's related to this package, but because I'm desperate looking for solution, maybe someone can give me some hints.

Short story, I'm facing 2 problems when deploying my react app to production.

1st I got error mimetype HTML is not supported. Something like this :

error OneSignalSDKWorker.js The script has an unsupported MIME type ('text/html').
After some research, I found that maybe this error happens because when I build the react using command : npm run build, it will serve all of the files using 1 index.html. That's why react can't find those js files.

I know this because when I try to direct accessing to https://mysite.com/OneSignalSDKWorker.js, it just found nothing and get caught to my react error handler route.

So, I try to add the OneSignalSDKWorker.js to my public folder in React and rebuild it. Here are the files : https://github.com/OneSignal/OneSignal-Website-SDK/releases/download/https-integration-files/OneSignal-Web-SDK-HTTPS-Integration-Files.zip

I got those files from here : https://documentation.onesignal.com/docs/onesignal-service-worker-faq

I also try to add these lines on my App.js, using react-helmet :

<Helmet>
      <script src="/OneSignalSDKWorker.js" type="text/javascript" />
      <script src="/OneSignalSDKUpdaterWorker.js" type="text/javascript" />
    </Helmet>

After adding those solutions, I'm quite confident that now those files is already served directly at https://mysite.com/OneSignalSDKWorker.js. Because when I access it, it doesn't get caught to my react error handler route. It opened.

But instead now it shows error like these :

Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Sorry, check with the site admin for error: EACCES ..

And when I access my main app, it shows error like this :

GET https://staging.cicle.app/OneSignalSDKWorker.js net::ERR_ABORTED 500 (Internal Server Error)
A bad HTTP response code (500) was received when fetching the script.
ServiceWorkerManager.js:399 [Service Worker Installation] Installing service worker failed TypeError: Failed to register a ServiceWorker for scope ('https://mysite.com/') with script ('https://mysite.com/OneSignalSDKWorker.js?appId=xxxxxxxxxxxxxxxxxxxxxxxxxxx'): A bad HTTP response code (500) was received when fetching the script.
(anonymous) @ ServiceWorkerManager.js:399
tslib.es6.js:63 Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('https://mysite.com/') with script ('https://mysite.com/OneSignalSDKWorker.js?appId=xxxxxxxxxxxxxxxxxxxxx'): A bad HTTP response code (500) was received when fetching the script.

Lastly, I don't understand why I need to cope with all of this stuff about service workers. because in localhost it works without setting up anything like this (start the project with only npm start, not npm run build). It just works using this package.

Here's my code in frontend :

import OneSignal, { useOneSignalSetup } from 'react-onesignal';

//Onesignal initialization
    const options = {
      notifyButton: {
        enable: true,
        size: 'small'
      }
    }
    OneSignal.initialize(process.env.REACT_APP_PUSH_NOTIF_APP_ID, options);

Specification :
Frontend : React js - create-react-app
Backend : NodeJS - express
Server : Linux Ubuntu 20.04, nginx

setExternalUserId causes user email to become "Never Subscribed"

I have tried many variations of the below code to troubleshoot ( with and without async. inline code. putting setExternalUserId inside a then after setEmail. Putting setEmail inside a callback after setExternalUserId)

await OneSignal.setEmail(email).then(() => {
    OneSignal.setExternalUserId("anystringhereunique");
  });

The above code will cause the user to become "Never Subscribed"
image
while if the code is simply

OneSignal.setEmail(email)

followed by no setExternalUserId the email will be fine and subscribed.
image
But I need to set the externalUserId because I am syncing this user with a mixpanel user via the $onesignal_user_id.

If I try to run

OneSignal.setSubscribed(true) 

following the setExternalUserId it will not do anything and the user will remain as "Never Subscribed"

Error when i try use bind in callback func

When i try use 'bind' in callback func the code bellow i received a error

const that = this.handleNotificationInit.bind(this);

        const events = [
            {
                listener: 'once',
                event: 'subscriptionChange',
                callback: that
            }
        ];

        OneSignal.initialize(baseNotificationId, {}, events);

"Uncaught SyntaxError: Unexpected identifier
at injectScript (index.es.js:120)
at injectModuleScript (index.es.js:137)
at Object.initialize (index.es.js:155)
at new App (App.tsx:151)
at new App (eval at ES6ProxyComponentFactory (react-hot-loader.development.js:NaN), :14:7)
at constructClassInstance (react-dom.development.js:14204)
at updateClassComponent (react-dom.development.js:18413)
at beginWork$1 (react-dom.development.js:20186)
at beginWork$$1 (react-dom.development.js:25756)
at performUnitOfWork (react-dom.development.js:24695)"

When i click in see more, i see this code:

 var OneSignal = window.OneSignal || [];
    OneSignal.push(function() {
      OneSignal.once('subscriptionChange', function () { [native code] });
      OneSignal.init({
        appId: "7f8af520-827f-43c2-811a-94727dc20e43",
        
      });
    });

[Bug]: removeExternalUserId throws error if Identity Verification is active

What happened?

If Identity Verification is active, calling removeExternalUserId throws changing external_user_id on players require passing external_user_id_auth_hash error.

Steps to reproduce?

1. Enable identity verification
2. Update the external user id with auth hash
3. Execute `removeExternalUserId` function

What did you expect to happen?

I expected it to remove the external user id from the player.

Relevant log output

Uncaught (in promise) 
Object {
  errors: Array [ "changing external_user_id on players require passing external_user_id_auth_hash" ]
  success: false
}

[question]: isPushNotificationsSupported not in interface?

How can we help?

How should I check if OneSignal is supported?

It does not appear to be in the interface and this is the error you get if you try:

OneSignal.isPushNotificationsSupported()

react_onesignal__WEBPACK_IMPORTED_MODULE_0__.default.isPushNotificationsSupported is not a function

Unable to initialize react-onesignal The script has an unsupported MIME type ('text/html')

I'm trying to initialize onesignal on my react app (where i have already checked my app id of onesignal it's correct).
But after it asks for permission to show notification I'm getting this worker error. When i have already removed the worker code from src/index.js

Error-
The script has an unsupported MIME type ('text/html').
[Service Worker Installation] Installing service worker failed SecurityError: Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/OneSignalSDKWorker.js?appId=xxxxxxx-d75e-4239-xxxx-xxxxxxxx'): The script has an unsupported MIME type ('text/html').

And I'm using this code to initialize.
OneSignal.initialize( 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', { notifyButton: { enable: true, }, allowLocalhostAsSecureOrigin: true, }, events, );
where events is
const events = [ { listener: 'once', event: 'subscriptionChange', callback: (isSubscribed) => { if (true === isSubscribed) { console.log('The user subscription state is now:', isSubscribed); } console.log('isSubscribed ----', isSubscribed); }, }, ];
Here i'm also not getting any logs from the event. Also even without these events I'm still getting the same error.

one signal throwing undefined

Hello, I've been having problem debugging my application at my website because one signal was throwing undefined, the source code is already minified at this stage.
Now, by looking at the code, I know that onesignal was not setup correctly from the start.
I'm gonna open a pull request for that

Uncaught (in promise) Error: OneSignal is not setup correctly

import ReactOneSignal from 'react-onesignal';
const options = { safari_web_id:"web.xxxxx-xxxxxx", allowLocalhostAsSecureOrigin: true, notifyButton:{ enable:true, } };
ReactOneSignal.initialize("xxxx-xxxxx-xxxxx-xx", options);

calling

ReactOneSignal.getPlayerId(function(userId) { console.log('user id', userId); });
results in the error above.

Am I missing anything in the initialization?

[question]: Async functions stay pending when testing in localhost

How can we help?

I set up a React test app on localhost:3000 and I configured my OneSignal app in the dashboard with the option ". I'm doing the following:

  1. Check if the OneSignal service worker isn't installed yet, and if it isn't, initialize OneSignal.
  2. After the init promise resolves, set the external user ID and show the category prompt.
  3. Then, I have a button to obtain the player ID. That button sets a state variable and triggers a useEffect, which calls the getUserId() method.

When the browser isn't subscribed to notifications and the OneSignal service worker isn't installed yet, I click on the allow button of the native prompt and then, without refreshing, click on the button to get the player ID, I can log it to the console without issue. However, when I refresh the page, I can no longer obtain the player ID because the async getUserId() method stays pending forever.

I have two questions:

  1. Is there some step I am missing when using the async methods of the SDK in a local testing environment?
  2. When I log the player ID to the console I don't see any network request done to the OneSignal API. Is it normal behavior?

I uploaded the test app to a repository here so you can check it out. You just have to put your app id in the constants object of the App.jsx file.

Onesignal setExtarnalId

Hi. I need to use setExternalId in my project. Can u implement this method to your component? Please help me about that.

No Document Object When Rendering Server Side

Hi,
We're running a headless wordpress site with react on the front end, and I was hoping to be able to use this package to easily incorporate OneSignal.
We utilize isomorphic rendering, and it looks like there might be an issue with server side rendering with react-onesignal, where it requires a document object when none exists.

Do you know of any workaround for this (or is it different issue altogether)?

This is currently in a component by itself, just doing the basic initialization:

'import ReactOneSignal from 'react-onesignal';
const OneSignal = (props) => {
const options = {
notifyButton: {
enable: true,
},
};
ReactOneSignal.initialize('', options)
return (
// return stuff
);
};
export default OneSignal;`

In the console, this yields the following:
render:error { url: '/', render:error err: render:error ReferenceError: document is not defined render:error at Object.initialize (/Users/me/site//node_modules/react-onesignal/src/oneSignal.ts:149:3) render:error at initialize (/Users/me/site//build/server/webpack:/components/oneSignal/index.js:87:20) render:error at processChild (/Users/me/site//node_modules/react-dom/cjs/react-dom-server.node.development.js:2871:14) render:error at resolve (/Users/me/site//node_modules/react-dom/cjs/react-dom-server.node.development.js:2795:5) render:error at ReactDOMServerRenderer.render (/Users/me/site//node_modules/react-dom/cjs/react-dom-server.node.development.js:3185:22) render:error at ReactDOMServerRenderer.read (/Users/me/site//node_modules/react-dom/cjs/react-dom-server.node.development.js:3144:29) render:error at renderToString (/Users/me/site//node_modules/react-dom/cjs/react-dom-server.node.development.js:3629:27) render:error at _callee$ (/Users/me/site//build/server/webpack:/server/serverRenderer.js:85:33) render:error at tryCatch (/Users/me/site//node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:62:40) render:error at Generator.invoke [as _invoke] (/Users/me/site//node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:288:22) } +0ms

OneSignal.initialized always undefined

I was trying to check if OneSignal object is initialized but it was always returning undefined. Had to use OneSignal.getOneSignalInstance().

export const execute = (callback) => {
  if (OneSignal.initialized) {
    callback();
  } else {
    const intervalHandler = setInterval(() => {
      if (OneSignal.initialized) {
        clearInterval(intervalHandler);
        callback();
      }
    }, 1000);
  }
};

React OneSignal 2.0 now in beta

๐Ÿšง 2.0 Beta Release ๐Ÿšง

Howdy!
We are happy to announce that we have released the 2.0 beta version of this package which includes several major changes.

Yarn

yarn add [email protected]

npm

npm install --save [email protected]

โš ๏ธ Includes breaking changes

If you are coming from <2.0, you will need to migrate if you choose to update the package.

Migration Guide

Review the updated documentation in the README.

Key Changes

  • Update your OneSignal initialization function (see below)
  • Remove the initialization hook (now handled for you automagically)
  • Event listeners are now set up using the on function
  • New functions supporting newer OneSignal features

The initialization function has been changed to match 1:1 with the underlying OneSignal WebSDK. The function has been renamed init. The appId is now set via the single config options argument passed to the init function:

import OneSignal from 'react-onesignal';

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

Furthermore, there is no longer a need to wrap the initialization in the useOneSignalSetup hook. The order of functions relative to the OneSignal initialization no longer matters (although we still recommend initializing OneSignal in a top-level component).

Event listeners can now be added directly via the on function. This function takes an event string and a callback.

We have added new functions to support the latest OneSignal functions and features.

Typings are included in the package automatically. See below for a full list of the functions included in this package:

interface OneSignal {
  init(options?: any): Promise<void>
  on(event: string, listener: Function): void
  off(event: string, listener: Function): void
  once(event: string, listener: Function): void
  isPushNotificationsEnabled(callback?: Action<boolean>): Promise<boolean>
  showHttpPrompt(options?: AutoPromptOptions): void
  registerForPushNotifications(options?: RegisterOptions): Promise<void>
  setDefaultNotificationUrl(url: string): void
  setDefaultTitle(title: string): void
  getTags(callback?: Action<any>): void
  sendTag(key: string,  value: any,  callback?: Action<Object>): Promise<Object | null>
  sendTags(tags: TagsObject<any>,  callback?: Action<Object>): Promise<Object | null>
  deleteTag(tag: string): Promise<Array<string>>
  deleteTags(tags: Array<string>,  callback?: Action<Array<string>>): Promise<Array<string>>
  addListenerForNotificationOpened(callback?: Action<Notification>): void
  setSubscription(newSubscription: boolean): Promise<void>
  showHttpPermissionRequest(options?: AutoPromptOptions): Promise<any>
  showNativePrompt(): Promise<void>
  showSlidedownPrompt(options?: AutoPromptOptions): Promise<void>
  showCategorySlidedown(options?: AutoPromptOptions): Promise<void>
  showSmsSlidedown(options?: AutoPromptOptions): Promise<void>
  showEmailSlidedown(options?: AutoPromptOptions): Promise<void>
  showSmsAndEmailSlidedown(options?: AutoPromptOptions): Promise<void>
  getNotificationPermission(onComplete?: Function): Promise<NotificationPermission>
  getUserId(callback?: Action<string | undefined | null>): Promise<string | undefined | null>
  getSubscription(callback?: Action<boolean>): Promise<boolean>
  setEmail(email: string,  options?: SetEmailOptions): Promise<string|null>
  setSMSNumber(smsNumber: string,  options?: SetSMSOptions): Promise<string | null>
  logoutEmail(): void
  logoutSMS(): void
  setExternalUserId(externalUserId: string | undefined | null,  authHash?: string): Promise<void>
  removeExternalUserId(): Promise<void>
  getExternalUserId(): Promise<string | undefined | null>
  provideUserConsent(consent: boolean): Promise<void>
  getEmailId(callback?: Action<string | undefined>): Promise<string | null | undefined>
  getSMSId(callback?: Action<string | undefined>): Promise<string | null | undefined>
  sendOutcome(outcomeName: string,  outcomeWeight?: number | undefined): Promise<void>
}

Summary

Consider the above changes when migrating to version 2 and make sure to thoroughly test your application.

Feedback

Please provide any feedback in the below thread during the Beta period to ensure we can address any potential issues.

Enjoy!

[question]: How can I invoke the sendSelfNotification method in a React Setup?

How can we help?

Issue:
Is there a way that I can invoke the sendSelfNotification method in a React Setup?

Error:
I get this error when that method is invoked:
Uncaught (in promise) TypeError: Vi.a.sendSelfNotification is not a function

Code snippet for testing sendSelfNotification method:

import OneSignal from 'react-onesignal';

const onOpen = async () => {
    const isPushEnabled = await OneSignal.isPushNotificationsEnabled();
    if (!isPushEnabled) {
      await OneSignal.registerForPushNotifications();
    } else {
      OneSignal.sendSelfNotification();
}

HTTPs not working with Chrome

Project

Used the 'react-onesignal' package inside a React Typescript project created with Vite.

Description

In a Chrome browser, native prompt simply refuses to open on any HTTPs site where the project is deployed, thus not registering the user and not receiving any notifications.

Reproducing Steps

  1. One Signal App

Screenshot 2022-03-28 at 1 25 39 PM

Screenshot 2022-03-28 at 1 27 26 PM

  1. Iintialization in React App
import OneSignal from "react-onesignal";
await OneSignal.init({ appId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" });

    const notfEnabled = await OneSignal.isPushNotificationsEnabled();

    if (!notfEnabled) {
      await OneSignal.showNativePrompt();

      if (await OneSignal.isPushNotificationsEnabled()) {
        OneSignal.setSubscription(true);
        const deviceID = await OneSignal.getUserId();
        console.log(deviceID);

        if (deviceID) dispatch(AddDevice(deviceID as string));
        else console.log("error in user ID", deviceID);
      }
    }

Versions

React One Signal - ^2.0.3
Chrome - 99.0.4844.83 (Official Build) (x86_64)
Firefox - 98.0.2 (64-bit)
Node - v16.13.2
NPM - 8.1.2

Calling any OneSignal function gives error - Uncaught (in promise) ReferenceError: react_onesignal__WEBPACK_IMPORTED_MODULE_1__ is not defined

After initializing OneSignal. Whenever i try to call any function or log OneSignal.initialized. I'm getting reference error.
Screenshot 2020-09-01 at 5 31 03 PM

initialize = async () => { const events = [ { listener: 'on', event: 'subscriptionChange', callback: async (isSubscribed) => { if (true === isSubscribed) { console.log('The user subscription state is now:', isSubscribed); console.log('OneSignal.initialized ----', OneSignal.initialized); // const currentState = await OneSignal.getNotificationPermission(); // console.log('currentState ----', currentState); // await OneSignal.registerForPushNotifications(); const playerId = await OneSignal.getPlayerId(); console.log('playerId ----', playerId); } console.log('isSubscribed ----', isSubscribed); }, }, ]; OneSignal.initialize( process.env.REACT_APP_ONE_SIGNAL_APP_ID, { autoRegister: true, notifyButton: { enable: true, }, allowLocalhostAsSecureOrigin: true, }, events, ); };

Wrong type on event callback.

Hi!
I've copy-pasted the example of the event handler

        [
          {
            listener: 'once',
            event: 'subscriptionChange',
            callback: isSubscribed => {
              if (isSubscribed === true) {
                console.log('The user subscription state is now:', isSubscribed)
              }
            },
          },
        ]

but I have a TS error:

(property) IOneSignalEvent.callback: IOneSignalEventCallback
Property 'callback' is missing in type '(isSubscribed: any) => void' but required in type 'IOneSignalEventCallback'.ts(2741)

TS wants an object like {callback: {callback: (result: any) => any}} instead of a simple {callback: (result: any) => any}

Here the d.ts file that causes the issue
https://github.com/pedro-lb/react-onesignal/blob/a6b249b71ce6ebc4f2091ad0d2f70b1a709bbc4c/package/src/oneSignal.types.ts#L61

Thank you for the beautiful project saved me a ton of time :)

ReferenceError indicating that callback is undefined thrown after user subscribes.

Here is the error message. It throws immediately after subscription, as a result the callback i defined does not work

VM201:5 Uncaught (in promise) ReferenceError: _callback is not defined at o.callback (<anonymous>:5:9) at o.n (Emitter.js:31) at o.<anonymous> (Emitter.js:113) at Generator.next (<anonymous>) at tslib.es6.js:65 at new Promise (<anonymous>) at Object.n (tslib.es6.js:61) at o.emit (Emitter.js:106) at Function.<anonymous> (Event.js:78) at Generator.next (<anonymous>) at tslib.es6.js:65 at new Promise (<anonymous>) at Object.n (tslib.es6.js:61) at Function.trigger (Event.js:56) at Function.triggerSubscriptionChanged (EventHelper.js:111) at Function.<anonymous> (EventHelper.js:34) at Generator.next (<anonymous>) at r (tslib.es6.js:62)

here is my implementation code

const events = [ { listener: 'once', event: 'subscriptionChange', callback:async (isSubscribed) => { if (true === isSubscribed) { console.log('The user subscription state is now:', isSubscribed); let device_id=await OneSignal.getPlayerId() await saveDeviceId(device_id) } }, }, { event: 'notificationDisplay', callback: (event) => { console.warn('OneSignal notification displayed:', event); }, }, { event: 'notificationDismiss', callback: (event) => { console.warn('OneSignal notification dismissed:', event); }, }, ]; React.useEffect(function(){ init(); },[should_reload_avatar,user]) async function init(){ try{ if(user !== null && user !== undefined){ //my app id goes here OneSignal.initialize("******* ******** ***************",{ allowLocalhostAsSecureOrigin:true },events) } } catch(e){ console.log(e) } } async function saveDeviceId(device){ appContext.setLoading(true); var response=await client.post('/save/user_device_id',{ 'device_id':device },{headers:getAuthHeader()}); appContext.setLoading(false); return response; }

The script has an unsupported MIME type ('text/html')[Bug]:

What happened?

I was setting up react-onesignal on my vite react app (https://documentation.onesignal.com/docs/react-js-setup). l perfectly configured everything with the worker, accessible at http://localhost:3000/OneSignalSDKWorker.js. The issue is on production. l can't access the OneSignalSDKWorker.js. Does this work only in development or ? Because l have tried like alot

Steps to reproduce?

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

What did you expect to happen?

l expect to find the OneSignalSDKWorker.js file after l deploy the app

Relevant log output

No response

Uncaught (in promise) TypeError: Type error

How can we help?

I am getting Uncaught (in promise) TypeError: Type error; when try to initialize the OneSignalSDK.

Here is my implementation

		OneSignal.init({
			appId,
			serviceWorkerPath: "OneSignalSDKWorker.js",
			allowLocalhostAsSecureOrigin: true,
			safari_web_id: process.env.NEXT_PUBLIC_SAFARI_WEB_ID
		}).then(() => {
			OneSignal.registerForPushNotifications()
		})

How can I solve this problem?

[Bug]: Uncaught (in promise) Error: You need to provide your OneSignal appId.

What happened?

Hi, iยดve a React (NextJS) application and i want to push some notifications to my users, but the OneSignal is not work in my QA application which is deployed in Azure DevOps. Its only works in my localhost oppened at 3000 port. How do i fix this?
My OneSignal appId is inside an enviroment file both locally and in qa.
In my OneSignal web-settings, the URL which was defined is my QA app, but when i change this to localhost its works perfectly

// init OneSignal in my _app.tsx file

useEffect(() => {
  OneSignal.init({ appId: process.env.NEXT_PUBLIC_ONESIGNAL_APP_ID || '' })
}, [])

Steps to reproduce?

1. Install react-onesignal package
2. Move OneSignalSDKWorker.js file to public folder  
3. Init OneSignal in _app.tsx file with useEffect hook
- 3.1. Create a .env.development.local and declare OneSignal appId as enviroment variable, in my deployed app i put the same enviroment variables
4. Deploy my app and wait build process
5. Error: You need to provide your OneSignal appId.

What did you expect to happen?

Expect to OneSignal works and show to users a push slide prompt

Relevant log output

Uncaught (in promise) Error: You need to provide your OneSignal appId.
    at _app-43f2d96f5f6b22f9.js:172:89514
    at new Promise (<anonymous>)
    at Object.init (_app-43f2d96f5f6b22f9.js:172:89453)
    at _app-43f2d96f5f6b22f9.js:172:99679
    at Ui (framework-93b89dc25365d5c7.js:1:104667)
    at t.unstable_runWithPriority (framework-93b89dc25365d5c7.js:1:122637)
    at Ql (framework-93b89dc25365d5c7.js:1:44986)
    at Fi (framework-93b89dc25365d5c7.js:1:104128)
    at bi (framework-93b89dc25365d5c7.js:1:95618)
    at framework-93b89dc25365d5c7.js:1:45209

OneSignalSDKWorker cannot be loaded

Description:

Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://cdn.onesignal.com/sdks/OneSignalSDKWorker.js' failed to load.
    at https://admin.easyecosystem.com/OneSignalSDKWorker.js:1:1

Hi recently we have been facing this issue while loading onesignal SDK and the worker SDK. I have attached an image containing the full error message. We have been using OneSignal for years but recently we encountered this issue.

Screenshot 2021-08-24 at 6 11 06 PM

Screenshot 2021-08-24 at 6 28 04 PM

Things we have checked before posting this issue

  1. Adblockers are disabled
  2. The worker sdk are correct path. The sdk location is correct if we click on the url from the console
  3. No third party extension running on the browsers

Browsers we have tested

  1. Chrome
  2. Brave
  3. Safari

Steps to Reproduce Issue:

  1. Visit https://staging.easyecosystem.com/#/
  2. Open console in browser. You will be able to see the error.

Anything else:

null

3.0.0 Beta Released!

๐Ÿšง Beta release. Please test thoroughly prior to production use. ๐Ÿšง

In this major version beta release for the OneSignal SDK, we are making a significant shift from a device-centered model to a user-centered model. A user-centered model allows for more powerful omni-channel integrations within the OneSignal platform.

For information please see the migration guide

We are seeking feedback! Please leave questions and comments in the thread below.

On the future of `react-onesignal`

Hi folks!

I'm creating this issue to make things clear.

As some of you may have noticed, react-onesignal has been transferred from my personal account to the official OneSignal organization.

This means that this package is now the official implementation of OneSignal for React and we're expecting great things to come, such as a better maintenance cycle, more contributors, and better quality.

The development cycle stays the same, and existing pull requests will be reviewed and published as needed.

For more information and/or suggestions, it's a great idea to create an issue or contact me or Rodrigo.

Cheers! ๐Ÿฅ‚

[TypeScript]: export types and interfaces for reuse (still missing export in 3.0.0)

What's on your mind?

For example, I want to make a React hook like

export const useOneSignal = (options?: Parameters<(typeof OneSignal)['init']['0']>): [ready: boolean, instance: typeof OneSignal]

and I have to use Parameters<(typeof OneSignal)['init']['0']> instead of IInitObject.

Export IInitObject and other types can make this function signature easier to write.

[question]: React PWA working in macOS android but not iOS home screen app problem with init

How can we help?

Hi,

Generally I have OneSignal working perfectly on macOS in browsers and on android but I am running into issues with the iOS home screen app.

I am triggering OneSignal.init in an async await function in my react pwa. This resolves fine in my osx browsers and android but not in iOS for some reason. I tried adding a .catch to the end of the init to no avail.

I think my manifest is fine as it is installing ok in both iOS and android and while I cannot check the Onesignal service worker in iOS I can track it in Chrome and all appears OK. Both manifest and sw are in my root folder of the pwa.

My manifest is:

{
    "short_name": "MyApp",
    "name": "MyApp",
    "icons": [
        {
            "src": "favicon.ico",
            "sizes": "64x64 32x32 24x24 16x16",
            "type": "image/x-icon"
        },
        {
            "src": "logo192.png",
            "type": "image/png",
            "sizes": "192x192",
            "purpose": "any maskable"
        },
        {
            "src": "logo512.png",
            "type": "image/png",
            "sizes": "512x512"
        }
    ],
    "start_url": ".",
    "display": "standalone",
    "theme_color": "#000000",
    "background_color": "#ffffff"
}

The only advice that I have seen online but have not really understood is that you have to register your sw in your index.js. Is this necessary? If so how should I do this for the OneSignalSDKWorker.js? I don't have any other sw running.

If you need any further details I will be happy to supply them.

An example for React JS App Ionic

Hello, I am trying to implement OneSignal using this package in my Ionic App.

I tried my best to implement but some code it gives no popup and some code gives error OneSignal not setup properly.

In App.tsx I have put following function and run on App load. But it says onesignal is not setup properly.

export async function NotificationAlert(){
    

  if(OneSignal.getOneSignalInstance())
    {

        const options = {
            autoResubscribe: true,
    autoRegister: true
        }
    
        OneSignal.initialize('639c84d3-6e70-4a61-9fa3-365fbe795c5a', options);
        OneSignal.registerForPushNotifications();
    }
     

}

then in useeffect, I am calling above function. With this code, nothing is happening.

[Bug]: My player id is unsubscribe when refresh (F5) my app

What happened?

#28

The problem exist in the new version!!

Steps to reproduce?

Hi, I have a problem, maybe my implementation is wrong, but I want your feedback, I've tried to implement onesignal on my reactjs web app (it's not react native).

I tried 3 differents aproachs:
1.- Following the oficial onesignal web push sdk documentation.
2.- This aproach.
3.- Using this aproach https://dev.to/devpato/push-notifications-in-reactjs-with-onesignal-5bon

All of them I've completed successfully, but all have a strange behavior on my reactjs web app.

When my app get the notifications permissions for first time and I accept it, it doesn't show the welcome notification and if I send a notification from my onesignal dashboard it doesn't show.

If I refresh (F5) my app two times and send another notification, it works and show correctly. But if for any reason I refresh again my app, the notifications don't work anymore and in my onesignal dashboard shows that my player id is unsubscribe.

Somebody has the same issue? or what could be wrong in my app? Thanks.

What did you expect to happen?

I expected to dont lose the connection when the user refresh the app

Relevant log output

No response

notificationDisplay event is not working in React app

I am getting push notifications but notificationDisplay event is not firing. I want to read data from notification pushed. I have also tried addListenerForNotificationOpened but it's also not working.

My Code

import { useEffect } from "react";
import OneSignal from "react-onesignal";

function App() {
  useEffect(() => {
    OneSignal.init({
      appId: "xxxxxx-xxxxxx-4e1f-bb5a-xxxxxxx",
    });

    OneSignal.addListenerForNotificationOpened(() => {
      console.log("hi");
    });

    OneSignal.on("addListenerForNotificationOpened", function (event) {
      console.log("Notification Clicked", event);
    });

    OneSignal.on("notificationDisplay", function (event) {
      console.log("OneSignal notification displayed:", event);
    });
    OneSignal.on("notificationDismiss", function (event) {
      console.log("OneSignal notification dismissed:", event);
    });
  }, []);

  const onHandleTag = (tag) => {
    OneSignal.sendTag("tech", tag).then(() => {
      console.log("tagged");
    });
  };

  return (
    <div>
      <h1> React one signal push notification demo</h1>
      <button onClick={() => onHandleTag("react")}>Click</button>
    </div>
  );
}

export default App;

[question]: Why is this library marked for React?

How can we help?

Just wondering why this library is packaged under a react label/why there isn't a vanilla npm package for one signal. Just wondering what the limitations are of it that rely on react.

I was able to install this package and use it inside of a solid-js app. Not a fan of using packages with CDNs due to no Typescript support/global variables. Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.