Code Monkey home page Code Monkey logo

onesignal-ngx's Introduction

welcome to onesignal-ngx ๐Ÿ‘‹

Version Documentation Maintenance Twitter: onesignal

This is a JavaScript module that can be used to easily include OneSignal code in a website that uses Angular 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.

Upgrading from Version 1? See our migration guide to get started.

Contents


Install

Yarn

yarn add onesignal-ngx

npm

npm install --save onesignal-ngx

Library setup

import { OneSignal } from 'onesignal-ngx';

Initialize OneSignal with your appId via the options parameter:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-example-app';

  constructor(private oneSignal: OneSignal) {
    this.oneSignal.init({
      appId: "8e7fe838-fbcd-4152-980d-32565a2dcf03",
    });
  }
}

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

Examples

await this.oneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' });
// do other stuff
this.oneSignal.init({ appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' }).then(() => {
  // 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 (full list of initialization options).

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.

Example:

this.oneSignal.init({
   appId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
   serviceWorkerParam: {
     scope: '<path scope>'
   },
   serviceWorkerPath: '<path>'
});

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 it 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 file is being served successfully.

Troubleshooting: If you uploaded the file but you cannot access it via your browser search bar, make sure you have told Angular about it via the assets param in your angular.json file.


Typescript

This package includes Typescript support.

class OneSignal {
	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

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

See the OneSignal WebSDK Reference for more info on the available event listeners.

Troubleshooting

Service Worker Issues

Check the serviceWorker flag

In your angular.json, see if the serviceWorker flag is set to true. The flag is used to cause the production build to include some extra service worker files that will conflict with the OneSignal worker if they use the same scope. If your web app depends on this flag being true and hence the Angular service worker (ngsw-worker.js) like in PWA setups, you should customize your OneSignal service worker integration to use a different scope than the Angular service worker. Otherwise, they will conflict. This can be done using the service worker OneSignal initialization params documented above. Click for further details.


๐Ÿค 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 MIT licensed.

Enjoy!

onesignal-ngx's People

Contributors

emawby avatar jkasten2 avatar jmadler avatar rgomezp avatar

Stargazers

 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

onesignal-ngx's Issues

[Bug]: subscriptionChange not being called

What happened?

subscriptionChange is not being triggered. I expect it to be called when permission has been granted and the web worker is loaded. Because of this we can't get the user id. We use this in a PWA, so we run it in Android and iOS, only after the app is closed and opened again we are able to get the user id.

The following issue seem to describe the same:
OneSignal/OneSignal-Android-SDK#749

What browsers are you seeing the problem on?

Chrome (Chromium), Safari

What operating system are you running?

PWA Android (and maybe iOS devices?)

Steps to reproduce?

// First init oneSignal
await this.oneSignal.init({
  appId: '{id}',
  autoResubscribe: true,
  allowLocalhostAsSecureOrigin: true,
  serviceWorkerParam: {
    scope: '/{scope}'
  },
  serviceWorkerPath: '/{path}'
});

// Listen to subscriptionChange
this.oneSignal.on('subscriptionChange', isSubscribed => {
  // This never gets called
  console.log('One signal subscription changed', isSubscribed);
  if (isSubscribed) {
    this.initAfterSubscription();
  }
});

const permission = await this.oneSignal.getNotificationPermission();
if (permission === 'denied') {
  return;
}

if (permission === 'default') {
  await this.oneSignal.showNativePrompt();
}

What did you expect to happen?

I expected to see the console log inside the subscriptionChange listener.

Relevant log output

No response

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

See our migration guide to get started.

We are seeking feedback. Please drop any questions or comments in the thread below.

Thank you

[Bug]: The notifications are not delivered, when using Angular pwa and OneSignal together

What happened?

Although I registered OneSignal different scope than PWA service worker, It's causing issues. In the devtools service workers tab this can be observed that OneSignal service worker is stopped accordingly the notifications are not delivered.

What browsers are you seeing the problem on?

Chrome (Chromium)

What operating system are you running?

Windows 11

Steps to reproduce?

Node version: 18.16.0
Angular version: 16.1.0
NPM version: 9.5.1
onesignal-ngx version: 2.0.1

I created a repo to reproduce the issue. https://github.com/ertugrulbakidal/AngularWithOneSignal

- Change the OneSignal app id
- Install dependencies
- run ng build
- npm install --global http-server
- npx http-server -p 4200 -c-1 .\dist\angular-pwa-with-one-signal\

What did you expect to happen?

The OneSignal notifications should be delivered while using Angular PWA

Relevant log output

No response

[Question]: How do we recover the Subscription ID?

How can we help?

Hi,

We have a Software that was using a legacy version of Angular (v10). We decided to carefully upgrade our project to v14. After this long migration process we've noticed that OneSignal were logging this error: OneSignal is not setup correctly. We've try reconfigure OneSignal and the error have persisted until we upgrade to the v2 using the Migration Guide recommendations. And now we can't find a way to get the subscription ID.


How do we recover the Subscription ID to integrate One Signal with others systems?

@jmadler @jkasten2 @emawby @rgomezp

logoutSms() not un-subscribing user from sms notifications

Description:
We have a chat system set up to send an sdk request to message each user with a given external ID each time they receive a message. When a user enables this feature we set their number with their external user ID using oneSignal.setSMSNumber('UsersNumber'), then when a user turns off this feature we call oneSignal.logoutSMS() so they will not receive any further sms messages. However after calling logoutSMS() the user can still receive sms messages and no change is reflected on the onesignal dashboard.

Environment

Installed through npm

Steps to reproduce issue:

  1. Set users external id with oneSignalService.setExternalUserId(_id)
  2. Register user number with oneSignal.setSMSNumber('UsersNumber')
  3. Call onesignal.logoutSMS()
  4. Send message to user using sdk call
    "channel_for_external_user_ids": "sms", "include_external_user_ids": ["_id"]
  5. User still receives sms message

[Bug]: Cannot access OneSignal.User.getTags() from Angular SDK

What happened?

I am using the Angular SDK from one-signal (v11). It allows me to addTags but when I try to access the method to getTags, it says the method is not available on User object [getTags is undefined]. On checking the declaration file, it seems that the method is not exposed from the package. If I try to access it from the console on the web-page, I am able to get the tags then.

import { OneSignal } from 'onesignal-ngx';
export class OneSignalSDKService {

  constructor(private oneSignal: OneSignalModule) {} 
  getMarketingPushNotificationState(): boolean {
      const tags = this.oneSignal.User.getTags();  // throws error at this line
      return (tags?.someValue == 'true');
  }

I have made sure that OneSignal initialization is already done and there are values in this.oneSignal and this.oneSignal.User.
I am also able to call the methods this.oneSignal.User.addTag() and this.oneSignal.User.addTags() with proper params.

What browsers are you seeing the problem on?

Firefox, Chrome (Chromium), Safari, Microsoft Edge

What operating system are you running?

Windows 10

Steps to reproduce?

1. Use `import { OneSignal } from 'onesignal-ngx';` in any angular app and call the init method with a valid app id.
2. Try to get the tags from the OneSignal object (inject as dependency in constructor as shown in the code above) this.oneSignal.User.getTags();

What did you expect to happen?

I should be able to get the list of tags and their values through that method. The method should be exposed from the declaration file of the npm package.

Relevant log output

No response

window not defined with angular universal ssr (Server Side Rendering)

I did integration of OneSignal with angular App.

This used to working fine with normal angular project.

After I added angular Universal it is giving error ReferenceError: window is not defined

This is the code where it stucks.

this.oneSignal.on('notificationDisplay', function (event) {
      console.log('New Notification:', event);
    });

Error installing from NPM

Using:-

npm install --save onesignal-ngx

results in:-

Found: @angular/[email protected]
npm ERR! node_modules/@angular/common
npm ERR! @angular/common@"~13.2.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^11.0.9" from [email protected]
npm ERR! node_modules/onesignal-ngx
npm ERR! onesignal-ngx@"*" from the root project

Argument type error after last update (1.0.1)

After the last update (1.0.0 -> 1.0.1) it is no longer possible to use the notificationDisplay and notificationDismiss events getting the event as a result, in compiling these lines:

this.oneSignal.on('notificationDisplay', (event: any) => {
    [USING event OBJECT]
})

I get this error:

TS2345: Argument of type '(event: any) => void' is not assignable to parameter of type '() => void'

Probably related to this:
#18 (comment)
Commit:
98045a3

OneSignal not working when "serviceWorker" set to true in angular.json

After some tests with different compile settings (local, staging, production) in an Angular app I deployed, I found out that if the flag "serviceWorker" is set to true in angular.json, then the application is not able to receive notifications nor correctly instantiates or handles the OneSignal provider.

The place where this setting must be removed or set to false, is specifically in the
projects -> app -> architect -> build -> configurations -> production setting,

Environment you discovered this bug in (run ng version)

  • Angular: 13.0.0
  • Ionic: 6.01

[Bug]:

What happened?

Error installing onegisnal-ngx package, using angular/cli version 7.0.4

What browsers are you seeing the problem on?

Firefox, Chrome (Chromium), Microsoft Edge

What operating system are you running?

Windows 11 Home

Steps to reproduce?

1. Install angular version 7.0.4.
2. Install npm onesignal-ngx
3. Build proyect "ng serve"
4. Error in browser
![image](https://user-images.githubusercontent.com/54013509/193499139-deca7f35-fb86-476b-9732-7e1e695f55ad.png)

What did you expect to happen?

Error installing onegisnal-ngx package, using angular/cli version 7.0.4

image
image

Relevant log output

No response

No Exported Member

When I try to import (import { OneSignalService } from 'onesignal-ngx';) I receive error:

The module '"onesignal-ngx"' don't have exported member 'OneSignalService'.ts(2305).

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.