Cordova SDK Setup

Instructions for adding the OneSignal SDK to your Cordova app for iOS, Android, and derivatives like Amazon

πŸ“˜

Looking for Ionic setup?

See our Ionic SDK Setup guide instead. This includes Ionic Cordova.

Step 1. Requirements

iOS Requirements

  • An iOS 9+ or iPadOS device (iPhone, iPad, iPod Touch) to test on. Xcode 14+ simulator works running iOS 16+.
  • A Mac with Xcode 12+.
  • An iOS Push Certificate.
  • Cordova [email protected] or newer.
  • CocoaPods - Install with the following from the Terminal:
sudo gem install cocoapods
pod repo update

Android Requirements

Amazon & Huawei Requirements

Follow these instructions if your app is distributed on the Amazon AppStore and/or the Huawei AppGallery.

Step 2. Import OneSignal Plugin

You should remove any other push SDKs that you are not using – otherwise, you may see duplicate notifications being sent to your users.

Run the following from your project directory:

cordova plugin add onesignal-cordova-plugin --save

Step 3. Add Required Code

Add the following to the bottom of the first Javascript file that loads with your app. This is <project-dir>/www/js/index.js for most Cordova projects.

// Add to index.js or the first page that loads with your app.
document.addEventListener('deviceready', OneSignalInit, false);
function OneSignalInit() {
    // Uncomment to set OneSignal device logging to VERBOSE  
    // window.plugins.OneSignal.setLogLevel(6, 0);
    
    // NOTE: Update the setAppId value below with your OneSignal AppId.
    window.plugins.OneSignal.setAppId("YOUR_ONESIGNAL_APP_ID");
    window.plugins.OneSignal.setNotificationOpenedHandler(function(jsonData) {
        console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
    });
    
    //Prompts the user for notification permissions.
    //    * Since this shows a generic native prompt, we recommend instead using an In-App Message to prompt for notification permission (See step 6) to better communicate to your users what notifications they will get.
    window.plugins.OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
        console.log("User accepted notifications: " + accepted);
    });
}

3.1 Update initialization parameters. Replace YOUR_ONESIGNAL_APP_ID with your OneSignal App Id, available in the OneSignal dashboard under Settings > Keys & IDs.

Step 4. Update Project Settings to Target Android 13 (Android Only)

Validate your target SDK version is at least version 33.

Requirements:

  • Cordova Android Platform 9.1.0 or higher
android {
    compileSdkVersion 33
    ...

    defaultConfig {
        ...
        targetSdkVersion 33
    }
}
11031103

Set the Compile Sdk Version to 33.

11031103

In Default Config, set the Target SDK Version to 33.

Step 5. Configure your Xcode project (iOS Only)

4.1 In /platforms/ios open the .wcworkspace project in Xcode.

  • Run xed platforms/ios from your project directory to do this.
    4.2 Select the root project, and under Signing & Capabilities, enable Push Notifications.
    4.3 Next, enable Background Modes and check Remote Notifications.
15121512

iOS Service Extensions

Highly recommended: This step is optional but highly recommended. The OneSignalNotificationServiceExtension allows your application (in iOS) to receive rich notifications with images and/or buttons, along with Badges and advanced analytics like Outcomes.

4.4 Please follow the Notification Service Extension guide (only Steps 2).

  • Use Objective-C in this step, then come back to this page and continue following the steps below.

4.5 Select the new OneSignalNotificationServiceExtension Target, select Build Settings, then search for Code Signing Entitlements.

4.6 Delete both Debug and Release entries so they are blank.

11391139

4.7 In the Project Navigator, select the top-level project directory and select the OneSignalNotificationServiceExtension target.

Ensure the Deployment Target is set to the same value as your Main Application Target. Unless you have a specific reason not to, you should set the Deployment Target to be iOS 10 which is the version of iOS that Apple released Rich Media for push. iOS versions under 10 will not be able to get Rich Media.

878878

This should be the same value as your Main Application Target.

4.8 Close Xcode and open platform/ios/Podfile
4.9 Add the following to the bottom of the file.

target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignalXCFramework', '>= 3.0.0', '< 4.0'
end

4.10 Open you terminal to platform/ios and run pod install

iOS - Add App Groups (Recommended)

In order for your application to use Confirmed Deliveries and increment/decrement Badges through push notifications, you need to setup an App Group for your application.

Please follow the iOS SDK App Groups setup guide to add the OneSignal App Group in your app.

iOS Automatic Builds (Optional)

If you are using an automated build system, you may run into issues where the Push Notification capability is not enabled for your project. In order to resolve this problem, you can follow these steps:

4.11 In your Xcode project, make sure the Push Notifications capability (as well as any other capabilities your app needs).

4.12 Close the Xcode project. In the /platforms/ios folder you will see a {yourProjectName}.entitlements file. Copy this file to the root of your Cordova project.

4.13 Edit your config.xml file to include the following. Make sure to replace [yourProjectName] with the name of your project.

<platform name="ios">
    <resource-file src="[yourProjectName].entitlements" />
</platform>

Step 6. Run Your App and Send Yourself a Notification

Run your app on a physical device to make sure it builds correctly. Note that the iOS Simulator does not support receiving remote push notifications.

  • Android and iOS devices should be prompted to subscribe to push notifications if you used the example setup code provided.

Check your OneSignal Dashboard Audience > All Users to see your Device Record.

Then head over to Messages > New Push to Send your first Push Notification from OneSignal.

πŸ“˜

Troubleshooting

If you run into any issues please see our Cordova Variants troubleshooting guide.

Try the example project on our Github repository.

If stuck, contact support directly or email [email protected] for help.

For faster assistance, please provide:

  • Your OneSignal App Id
  • Details, logs, and/or screenshots of the issue.
  • Steps to reproduce

Step 7. Set Custom User Properties

Recommended
After initialization, OneSignal will automatically collect common user data by default. Use the following methods to set your own custom userIds, emails, phone numbers, and other user-level properties.

Set External User Id

Required if using integrations.
Recommended for messaging across multiple channels (push, email, sms).

OneSignal creates channel-level device records under a unique Id called the player_id. A single user can have multiple player_id records based on how many devices, email addresses, and phone numbers they use to interact with your app.

If your app has its own login system to track users, call setExternalUserId at any time to link all channels to a single user. For more details, see External User Ids.

let externalUserId = '123456789'; // You will supply the external user id to the OneSignal SDK
window.plugins.OneSignal.setExternalUserId(externalUserId);

Set Email and Phone Number

Recommended if using Email and SMS messaging.
Use the provided SDK methods to capture email and phone number when provided. Follow the channel quickstart guides for setup:

// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.setEmail("[email protected]");

// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.setSMSNumber("+11234567890");

Data Tags

Optional
All other event and user properties can be set using Data Tags. Setting this data is required for more complex segmentation and message personalization.

window.plugins.OneSignal.sendTags({key: "value", key2: "value2"});

Step 8. Implement a Soft-Prompt In-App Message

Optional

It is recommended that apps create an alert, modal view, or other interface that describes the types of information they want to send and gives people a clear way to opt in or out.

OneSignal provides an easy option for a "soft-prompt" using In-App Messages to meet this recommendation and have a better user experience. This also permits you to ask for permission again in the future, since the native permission prompt can no longer be shown in your app if the user clicks deny.

See our How to Prompt for Push Permissions with an In-App Message Guide for details on implementing this.

Step 9. Add Android Icons (Android Only)

Follow the Android Notification Icons instructions to create small notification icons.

Step 10. Add Amazon ADM Support (Kindle Fire Apps Only)

Place your api_key.txt file into your <project-dir>/platforms/android/assets/ folder.
To create an api_key.txt for your app, follow our Generate an Amazon API Key.

πŸ‘

Setup Complete!

Visit Mobile Push Tutorials for next steps.


What’s Next