# Cordova SDK Basic integration guide

This section contains information on how to integrate the Pushwoosh Cordova SDK into your application.

## Prerequisites

To integrate the Pushwoosh Cordova SDK into your app, you will need the following:

<Aside type="note" title="Requirements">
 - A [Pushwoosh account](https://sso.pushwoosh.com/login).
 - A [Pushwoosh project](/product/first-steps/start-with-your-project/create-your-project) set up in your account.
 - **For iOS integration:**
    - An iOS platform configured to send push notifications. We recommend using the [Token-Based Authentication configuration](/developer/first-steps/connect-messaging-services/ios-configuration/ios-token-based-configuration/) as the simplest approach.
    - Set the Gateway to `Sandbox` to send pushes to a simulator.
 - **For Android integration:**
    - A [configured Android platform](/developer/first-steps/connect-messaging-services/android-configuration/android-firebase-configuration)
    - The `google-services.json` file and `package name` from your Firebase project.
    - A Firebase project connected to your Android application. Follow the [Firebase setup guide](https://firebase.google.com/docs/android/setup#manually_add_firebase) if needed.
 - Your `Pushwoosh Application Code` and [Pushwoosh Device API Token](/developer/api-reference/api-access-token/#device-api-token) from the Pushwoosh Control Panel for your application.
</Aside>

## Integration steps

### 1. Add Pushwoosh Cordova SDK Dependency

Add the Pushwoosh Cordova SDK dependency to your project:

```bash
cordova plugin add pushwoosh-cordova-plugin
```

### 2. Cordova SDK Initialization

In the root component of your `index.js` file, add the following code inside the `deviceready` event handler. Follow the steps in exact order:

```javascript title="index.js"
document.addEventListener('deviceready', function() {
    var pushwoosh = cordova.require("pushwoosh-cordova-plugin.PushNotification");

    // 1. Register notification callbacks before initialization
    document.addEventListener('push-receive', function(event) {
        var notification = event.notification;
        console.log("Push received: " + JSON.stringify(notification));
    });

    document.addEventListener('push-notification', function(event) {
        var notification = event.notification;
        console.log("Push opened: " + JSON.stringify(notification));
    });

    // 2. Initialize Pushwoosh
    pushwoosh.onDeviceReady({
        appid: "__YOUR_APP_ID__"
    });

    // 3. Register the device to receive push notifications
    pushwoosh.registerDevice(
        function(status) {
            var pushToken = status.pushToken;
            // Handle successful registration
        },
        function(status) {
            // Handle registration error
        }
    );
}, false);
```

Where:
- `__YOUR_APP_ID__` is the application code from the Pushwoosh Control Panel.

<Aside type="caution" title="Initialization order matters">
The initialization sequence **must** follow the exact order shown above:

1. **Register event listeners first** (`push-receive`, `push-notification`)
2. **Then** call `onDeviceReady()`
3. **Then** call `registerDevice()`

Changing this order can cause the following issues:

- **Event listeners registered after `onDeviceReady()`:** If the app was launched by tapping a push notification (cold start), `onDeviceReady()` immediately delivers the launch notification payload to JavaScript. If your listeners are not yet registered at that point, **the launch notification is lost** with no way to recover it.
- **`registerDevice()` called before `onDeviceReady()`:** The native SDK may not be properly configured with your App ID yet, which can cause the device registration to fail silently or return an error.
- **Event listeners registered after `registerDevice()`:** Any push notification that arrives and is processed before your listeners are in place will be dispatched as a DOM event and **silently dropped** since there is no replay mechanism in the plugin.

The plugin does not queue or buffer missed events on the JavaScript side. DOM events fired by `document.dispatchEvent()` are delivered only to listeners that are already registered at the time of dispatch.
</Aside>


### 3. iOS Native Setup

#### 3.1 Capabilities

To enable Push Notifications in your project, you need to add certain capabilities.

In the Signing & Capabilities section, add the following capabilities:
- `Push Notifications`
- `Background Modes`. After adding this capability, check the box for `Remote notifications`.

If you intend to use Time Sensitive Notifications (iOS 15+), also add the `Time Sensitive Notifications` capability.

#### 3.2 Info.plist

In your `Runner/Info.plist` set the `__PUSHWOOSH_DEVICE_API_TOKEN__` key to the [Pushwoosh Device API Token](/developer/api-reference/api-access-token/#device-api-token):
```swift title="info.plist"
<key>Pushwoosh_API_TOKEN</key>
<string>__PUSHWOOSH_DEVICE_API_TOKEN__</string>
```

#### 3.3 Message delivery tracking

You must add a Notification Service Extension target to your project. This is essential for accurate delivery tracking and features like Rich Media on iOS. 

Follow the [native guide’s steps](/developer/pushwoosh-sdk/ios-sdk/setting-up-pushwoosh-ios-sdk/basic-integration-guide/#4-message-delivery-tracking) to add the extension target and the necessary Pushwoosh code within it.

### 4. Android Native Setup

#### 4.1 Install dependencies

Ensure that the required dependencies and plugins are added to your Gradle scripts:

Add the Google Services Gradle plugin to your project-level `build.gradle` dependencies:

```groovy title="android/build.gradle"
buildscript {
  dependencies {
    classpath 'com.google.gms:google-services:4.3.15'
  }
}
```

Apply the plugin in your app-level `build.gradle` file:

```groovy title="app/build.gradle"
apply plugin: 'com.google.gms.google-services'
```

#### 4.2 Add Firebase configuration file

Place the `google-services.json` file into `android/app` folder in your project directory.

#### 4.3 Add Pushwoosh metadata

In your `main/AndroidManifest.xml` add [Pushwoosh Device API Token](/developer/api-reference/api-access-token/#device-api-token) inside the  `<application>` tag:

```xml title="AndroidManifest.xml"
<meta-data android:name="com.pushwoosh.apitoken" android:value="__YOUR_DEVICE_API_TOKEN__" />
```

> **Important:** Be sure to give the token access to the right app in your Pushwoosh Control Panel. [Learn more](/developer/api-reference/api-access-token/#edit-token)

### 5. Run the Project

1. Build and run the project.
2. Go to the Pushwoosh Control Panel and [send a push notification](/product/messaging-channels/push-notifications/send-push-notifications/one-time-push).
3. You should see the notification in the app.

## Extended integration

At this stage, you have already integrated the SDK and can send and receive push notifications. Now, let’s explore the core functionality

### Push notification event listeners

In the Pushwoosh SDK there are two event listeners, designed for handling push notifications:

- `push-receive` event is triggered when a push notification is received while the app is in the foreground
- `push-notification` event is triggered when a user opens a notification

These event listeners **must** be registered **before** calling `onDeviceReady()`, as shown in the [initialization step above](#2-cordova-sdk-initialization). You can customize the handler logic to suit your needs:

```javascript title="index.js"
// Register before onDeviceReady()
document.addEventListener('push-receive', function(event) {
    var message = event.notification.message;
    var payload = event.notification.userdata;
    console.log("Push received: " + message);
    // Add your custom logic here
});

document.addEventListener('push-notification', function(event) {
    var message = event.notification.message;
    var payload = event.notification.userdata;
    console.log("Push accepted: " + message);
    // Add your custom logic here (e.g., navigate to a specific screen)
});
```

### User configuration

By focusing on individual user behavior and preferences, you can deliver personalized content, leading to increased user satisfaction and loyalty

```javascript
class Registration {
  afterUserLogin(user) {

    // Set user ID
    pushwoosh.setUserId(user.getId());
    
    // Setting additional user information as tags for Pushwoosh
    pushwoosh.setTags({
      "age": user.getAge(),
      "name": user.getName(),
      "last_login": user.getLastLoginDate()
    });
  }
}
```

### Tags

Tags are key-value pairs assigned to users or devices, allowing segmentation based on attributes like preferences or behavior, enabling targeted messaging.

```javascript
class UpdateUser {
  afterUserUpdateProfile(user) {

    // Set list of favorite categories
    pushwoosh.setTags({
      "favorite_categories": user.getFavoriteCategoriesList()
    });
    
    // Set payment information
    pushwoosh.setTags({
      "is_subscribed": user.isSubscribed(),
      "payment_status": user.getPaymentStatus(),
      "billing_address": user.getBillingAddress()
    });
  }
}
```

### Events

Events are specific user actions or occurrences within the app that can be tracked to analyze behavior and trigger corresponding messages or actions

```javascript
class Registration {

  // Track login event
  afterUserLogin(user) {
    pushwoosh.postEvent("login", {
      "name": user.getName(),
      "last_login": user.getLastLoginDate()
    });
  }

  // Track purchase event
  afterUserPurchase(product) {
    pushwoosh.postEvent("purchase", {
      "product_id": product.getId(),
      "product_name": product.getName(),
      "price": product.getPrice(),
      "quantity": product.getQuantity()
    });
  }
}
```

## Troubleshooting

If you encounter any issues during the integration process, please refer to the [support and community](/developer/pushwoosh-sdk/support-and-community) section.