> For the complete documentation index, see [llms.txt](https://docs.webtonative.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.webtonative.com/javascript-apis/webtonative-notifications.md).

# Webtonative Notifications

Functions to manage push notifications sent through WebToNative's own notification service like subscribe, unsubscribe, saving tags, etc.

From your website you can subscribe or unsubscribe the device, check whether it is subscribed, save tags on the device for targeting (for example `plan` or `city`), and link the device to your own user id so you can send notifications to a specific user.

> You'll need to import the javascript file in your website before starting from this [link](https://docs.webtonative.com/javascript-apis/getting-started).

> **Platform support:** Android and iOS. Every function works on both platforms unless a platform note says otherwise.

> **Enable it first:** WebToNative Notification must be turned on for your app in the WebToNative dashboard.

***

## How the Functions Reply

Every `WTN.Notification` function returns a Promise. A call ends in one of three ways, and each one goes in a different place in your code:

| Outcome          | Where it lands | What it means                                                                                     |
| ---------------- | -------------- | ------------------------------------------------------------------------------------------------- |
| Rejected         | `.catch`       | The call was invalid (wrong input, or the page isn't inside a WebToNative app). Nothing was sent. |
| `success: false` | `.then`        | The request failed or the app couldn't communicate, e.g. no connection. Try again later.          |
| `success: true`  | `.then`        | The request completed. For `isSubscribed`, read `status` for the answer.                          |

**The promise resolves even when the request fails.** Always check `response.success` in `.then`.

```javascript
window.WTN.Notification.getTags()
  .then(function (response) {
    if (!response.success) {
      // The request failed or the app couldn't communicate. Try again later.
      return;
    }
    // The request completed. Use the response here.
  })
  .catch(function (error) {
    // The call was invalid. See "Errors" below.
    console.error(error);
  });
```

### Errors

A promise rejects only in these cases. The rejection value is a plain string.

| When                                                                                                          | Message                                                          | Fix                                                                                       |
| ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Any function is called outside a WebToNative app (e.g. in a desktop browser)                                  | `"This function will work in Native App Powered By WebToNative"` | Only call these functions inside the app. Use `.catch` to hide notification UI elsewhere. |
| `setTag()` is called with no argument, `null`, or `undefined`                                                 | `"data is required"`                                             | Pass an object of tags, e.g. `setTag({ plan: "premium" })`.                               |
| `removeTag()` is called with an empty string, an empty array, an array containing non-strings, or no argument | `"data must be a non-empty string or array of strings"`          | Pass an array of tag keys, e.g. `removeTag(["plan"])`.                                    |
| `setExternalUserId()` is called with no argument or an empty string `""`                                      | `"id is required"`                                               | Pass your user's id as a non-empty string, e.g. `setExternalUserId("u123")`.              |

***

## Subscribe

Subscribes this device to notifications. If notifications aren't allowed yet, the app asks the user for you, so you don't need to request the permission yourself first.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Notification.subscribe()
  .then(function (response) {
    if (response.success) {
      // Subscribed. Your code: e.g. show "Notifications on".
    } else {
      // Not subscribed. Your code: e.g. "Turn on notifications in Settings to get updates."
    }
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { subscribe } from "webtonative/Notification";

subscribe()
  .then((response) => {
    if (response.success) {
      // Subscribed. Your code: e.g. show "Notifications on".
    } else {
      // Not subscribed. Your code: e.g. "Turn on notifications in Settings to get updates."
    }
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**How the permission is asked:**

* If the user hasn't answered the permission dialog yet, the system dialog is shown.
* If the dialog can't be shown (the user denied it before, or turned notifications off), the app opens its notification settings. The reply waits until the user comes back to the app.

**Response:**

| Key       | Type      | Description                                                                                                    |
| --------- | --------- | -------------------------------------------------------------------------------------------------------------- |
| `success` | `Boolean` | `true` if the device is now subscribed. `false` if the user didn't allow notifications, or the request failed. |

**Example response:**

```json
{ "success": true }
```

***

## Unsubscribe

Unsubscribes this device. It stops receiving notifications until `subscribe` is called again. The notification permission itself is not changed.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Notification.unsubscribe()
  .then(function (response) {
    if (!response.success) {
      // The request failed or the app couldn't communicate. Try again later.
    }
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { unsubscribe } from "webtonative/Notification";

unsubscribe()
  .then((response) => {
    if (!response.success) {
      // The request failed or the app couldn't communicate. Try again later.
    }
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**Response:**

| Key       | Type      | Description                                                                                              |
| --------- | --------- | -------------------------------------------------------------------------------------------------------- |
| `success` | `Boolean` | `true` if the device is now unsubscribed. `false` if the request failed or the app couldn't communicate. |

***

## Is Subscribed

Tells you whether this device is currently subscribed. Use it to set the state of a "Notifications" toggle on your settings page.

**Read `status` for the answer, not `success`.** `success: true` means the check completed, and the device may be subscribed or not. `success: false` means the check itself couldn't be completed.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Notification.isSubscribed()
  .then(function (response) {
    if (!response.success) {
      // Couldn't check. Try again later.
      console.error(response.error);
      return;
    }
    if (response.status === "SUBSCRIBED") {
      // Subscribed
    } else {
      // Not subscribed
    }
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { isSubscribed } from "webtonative/Notification";

isSubscribed()
  .then((response) => {
    if (!response.success) {
      // Couldn't check. Try again later.
      console.error(response.error);
      return;
    }
    if (response.status === "SUBSCRIBED") {
      // Subscribed
    } else {
      // Not subscribed
    }
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**Response:**

| Key       | Type      | Description                                                                                   |
| --------- | --------- | --------------------------------------------------------------------------------------------- |
| `success` | `Boolean` | `true` if the check completed. `false` if the request failed or the app couldn't communicate. |
| `status`  | `String`  | Present when `success` is `true`. The device's subscription state. See the values below.      |
| `error`   | `String`  | Present when `success` is `false`. A short description of what went wrong, for logging.       |

**`status` values:**

| Value          | Meaning                                                         |
| -------------- | --------------------------------------------------------------- |
| `SUBSCRIBED`   | The device is subscribed and receives notifications.            |
| `UNSUBSCRIBED` | The device is not subscribed. Call `subscribe` to subscribe it. |

Compare against `"SUBSCRIBED"` and treat any other value as not subscribed, as in the example above.

**Example responses:**

```json
{ "success": true, "status": "SUBSCRIBED" }
{ "success": true, "status": "UNSUBSCRIBED" }
{ "success": false, "error": "Network error: timeout" }
```

***

## Tags

Tags are key-value pairs saved on this device, such as `plan: "premium"` or `city: "Delhi"`. Use them to send notifications to a group of devices, for example everyone on the premium plan. You can set, read and remove them from your website.

### Set Tag

Pass an object of tags. A key that already exists takes the new value.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Notification.setTag({ plan: "premium", city: "Delhi" })
  .then(function (response) {
    // response: { success: true }
    if (!response.success) {
      // The tags weren't saved. Try again later.
    }
  })
  .catch(function (error) {
    console.error(error); // see Errors below
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { setTag } from "webtonative/Notification";

setTag({ plan: "premium", city: "Delhi" })
  .then((response) => {
    // response: { success: true }
    if (!response.success) {
      // The tags weren't saved. Try again later.
    }
  })
  .catch((error) => {
    console.error(error); // see Errors below
  });
```

{% endtab %}
{% endtabs %}

### Get Tags

Takes nothing. On success, `response.tags` holds every tag on this device, or `{}` if there are none.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Notification.getTags()
  .then(function (response) {
    // response: { success: true, tags: { plan: "premium", city: "Delhi" } }
    if (!response.success) {
      // Couldn't read the tags. Try again later.
      return;
    }
    console.log(response.tags.plan); // "premium"
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { getTags } from "webtonative/Notification";

getTags()
  .then((response) => {
    // response: { success: true, tags: { plan: "premium", city: "Delhi" } }
    if (!response.success) {
      // Couldn't read the tags. Try again later.
      return;
    }
    console.log(response.tags.plan); // "premium"
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

### Remove Tag

Pass an array of the tag keys to remove. **Use an array even for one key**, e.g. `removeTag(["plan"])`.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Notification.removeTag(["plan", "city"])
  .then(function (response) {
    // response: { success: true }
    if (!response.success) {
      // The tags weren't removed. Try again later.
    }
  })
  .catch(function (error) {
    console.error(error); // see Errors below
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { removeTag } from "webtonative/Notification";

removeTag(["plan", "city"])
  .then((response) => {
    // response: { success: true }
    if (!response.success) {
      // The tags weren't removed. Try again later.
    }
  })
  .catch((error) => {
    console.error(error); // see Errors below
  });
```

{% endtab %}
{% endtabs %}

### What the tag functions return

All three resolve with `{ success: true }` when the request completed, and `getTags` adds `tags`. `success: false` means the request failed or the app couldn't communicate. Try again later.

### Tag Errors

| When                                                                                | What happens                                                                           | Fix                                                 |
| ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------- |
| `setTag()` is called with nothing, `null` or `undefined`                            | Rejects with `"data is required"`. Nothing is sent.                                    | Pass an object, e.g. `setTag({ plan: "premium" })`. |
| `setTag()` is given something other than an object, such as an array or a string    | Resolves with `success: false`. Nothing is saved.                                      | Pass an object of key-value pairs.                  |
| `removeTag()` is called with nothing, `""`, `[]`, or an array with non-string items | Rejects with `"data must be a non-empty string or array of strings"`. Nothing is sent. | Pass an array of keys, e.g. `removeTag(["plan"])`.  |

**Notes:**

* `setTag` doesn't send the tags back. Call [`getTags`](#get-tags) to read them.

***

## Set External User Id

Links this device to your own user id, so you can send notifications to that user instead of to a device. Call it after your user signs in. If you already use `WTN.User.login`, you don't need this: `login` links the user for you.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Notification.setExternalUserId("u123")
  .then(function (response) {
    if (!response.success) {
      // The device wasn't linked. Try again later, e.g. on the next app open.
    }
  })
  .catch(function (error) {
    console.error(error); // e.g. "id is required"
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { setExternalUserId } from "webtonative/Notification";

setExternalUserId("u123")
  .then((response) => {
    if (!response.success) {
      // The device wasn't linked. Try again later, e.g. on the next app open.
    }
  })
  .catch((error) => {
    console.error(error); // e.g. "id is required"
  });
```

{% endtab %}
{% endtabs %}

Pass your user's id as a string, e.g. `setExternalUserId("u123")`.

**Response:**

| Key       | Type      | Description                                                                                                      |
| --------- | --------- | ---------------------------------------------------------------------------------------------------------------- |
| `success` | `Boolean` | `true` if the request completed. `false` if the request failed or the app couldn't communicate. Try again later. |

**Errors:**

| When                                            | What happens                                                  | Fix                       |
| ----------------------------------------------- | ------------------------------------------------------------- | ------------------------- |
| Called with no argument or an empty string `""` | The promise rejects with `"id is required"`. Nothing is sent. | Pass a non-empty user id. |
| `id` contains only spaces                       | The promise resolves with `success: false`. Nothing is sent.  | Pass a real user id.      |

**Notes:**

* Calling it again with a different id moves the device to the new user. You don't need to call `removeExternalUserId` first.
* [`removeExternalUserId`](#remove-external-user-id) or `WTN.User.logout()` unlinks the user later.

***

## Remove External User Id

Unlinks the user from this device **and logs out the session**, exactly like `WTN.User.logout()`: the session is cleared and the page reloads. The device stays subscribed and keeps receiving notifications, but no longer as that user.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Notification.removeExternalUserId().then(function (response) {
  console.log(response.success); // always true
});
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { removeExternalUserId } from "webtonative/Notification";

removeExternalUserId().then((response) => {
  console.log(response.success); // always true
});
```

{% endtab %}
{% endtabs %}

**Response:**

| Key       | Type      | Description                                         |
| --------- | --------- | --------------------------------------------------- |
| `success` | `Boolean` | Always `true`, whether or not a user id was linked. |

**Notes:**

* The reply arrives just before the page reloads, so keep the code in `.then` short. Don't start navigation or network requests there.
* To change which user the device belongs to *without* logging out, call `setExternalUserId()` with the new id instead.

***

## Notification Permission

`subscribe` already asks for the permission when needed. Use the Permission functions when you want to show your own UI first, for example a "Turn on notifications" banner shown only when the permission is missing. `check` and `request` return a promise, like `WTN.Notification`. The promise is rejected when the page isn't inside a WebToNative app.

### Check

Reads the permission without showing a dialog. The reply arrives after about one second.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Permission.check({ permissions: ["notification"] })
  .then(function (data) {
    console.log(data.permissionStatus.notification); // e.g. "NOT_ALLOWED"
  })
  .catch(function () {
    // Not running inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { check } from "webtonative/Permission";

check({ permissions: ["notification"] })
  .then((data) => {
    console.log(data.permissionStatus.notification); // e.g. "NOT_ALLOWED"
  })
  .catch(() => {
    // Not running inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**Example response:**

```json
{ "permissionStatus": { "notification": "NOT_ALLOWED" } }
```

### Request

Shows the system dialog when the permission is not granted yet. If it is already granted, or permanently blocked, the reply comes at once with no dialog. On iOS the dialog can be shown only once; after a denial, later calls reply `PERMANENTLY_BLOCKED`.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Permission.request({ permission: "notification" })
  .then(function (data) {
    console.log(data.status); // e.g. "ALLOWED"
  })
  .catch(function () {
    // Not running inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { request } from "webtonative/Permission";

request({ permission: "notification" })
  .then((data) => {
    console.log(data.status); // e.g. "ALLOWED"
  })
  .catch(() => {
    // Not running inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**Example response:**

```json
{ "status": "ALLOWED" }
```

### Open Settings

Opens the app's notification settings, so the user can turn notifications on after denying them for good. With `alertDialogStyle`, a confirmation dialog is shown first. **There is no reply**: call `check` again when the user comes back.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.Permission.open({
  permission: "notification",
  alertDialogStyle: {
    title: "Notifications are off",
    message: "Turn on notifications in Settings to get order updates.",
    positiveText: "Open Settings",
    negativeText: "Not now",
  },
});
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { open } from "webtonative/Permission";

open({
  permission: "notification",
  alertDialogStyle: {
    title: "Notifications are off",
    message: "Turn on notifications in Settings to get order updates.",
    positiveText: "Open Settings",
    negativeText: "Not now",
  },
});
```

{% endtab %}
{% endtabs %}

Always pass `permission: "notification"`. To show a confirmation dialog before Settings opens, add `alertDialogStyle` with any of `title`, `message`, `positiveText` and `negativeText`. Leave out `alertDialogStyle` to open Settings directly.

### Permission status values

Used in `status` (request) and `permissionStatus.notification` (check):

| Status                | Meaning                                                                                             |
| --------------------- | --------------------------------------------------------------------------------------------------- |
| `ALLOWED`             | Granted.                                                                                            |
| `NOT_ALLOWED`         | Not granted, and a dialog can still be shown (never asked, or denied once).                         |
| `PERMANENTLY_BLOCKED` | Denied for good ("Don't ask again" on Android, denied on iOS). The user must change it in settings. |
| `RESTRICTED`          | Blocked by a system policy. iOS only.                                                               |
| `UNKNOWN_STATUS`      | Cannot be determined.                                                                               |

***

## Linking Users with WTN.User

The [User](https://docs.webtonative.com/javascript-apis/unified-user-session.md) functions manage the app's user session. While WebToNative Notification is enabled, `WTN.User.login`, `WTN.User.setUserInfo` and `WTN.User.logout` also link the logged-in user to this device, so you don't need to call `setExternalUserId` separately when you already use them.

### Fields used for notifications

| Field                  | Type      | Used for                                                                           |
| ---------------------- | --------- | ---------------------------------------------------------------------------------- |
| `externalUserId`       | `String`  | The user's id on this device. Required for `login`.                                |
| `userId`               | `String`  | Older name for the id; read only when `externalUserId` is missing or blank.        |
| `email`                | `String`  | The user's email on this device. Blank values are ignored.                         |
| `meta`                 | `Object`  | Custom data saved with the user on this device, for targeting (see below).         |
| `syncWithNotification` | `Boolean` | `false` skips linking the user to this device for this call. Leaving it out links. |

Other fields (`name`, `phone`, `token`, …) are kept in the session only. Nothing is linked while WebToNative Notification is disabled, or when there is no `externalUserId` / `userId`.

### How `meta` is handled

* `meta` must be an object. It is merged into what's already saved: existing keys stay, new keys are added, and a key sent again takes the new value.
* These names are reserved and removed from `meta`: `appId`, `platform`, `token`, `appVersion`, `timezone`, `deviceOs`, `deviceType`, `deviceModel`, `country`.
* The saved `meta` is kept after `logout()`.
* `meta` is ignored when nothing is linked (`syncWithNotification: false`, WebToNative Notification disabled, or no user id).

### Login

Logs a user in and links them to this device. The second argument (`options`) is merged into the first.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.User.login(
  {
    externalUserId: "u123",
    email: "a@b.com",
    name: "Asha",
    phone: "+911234567890",
    meta: { plan: "premium", city: "Pune" },
  },
  { syncWithNotification: true }
).then(function (response) {
  console.log(response.success);
});
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { login } from "webtonative/User";

login(
  {
    externalUserId: "u123",
    email: "a@b.com",
    name: "Asha",
    phone: "+911234567890",
    meta: { plan: "premium", city: "Pune" },
  },
  { syncWithNotification: true }
).then((response) => {
  console.log(response.success);
});
```

{% endtab %}
{% endtabs %}

* Logging in while a user is already logged in fails and the session stays unchanged. Call `logout()` first, or use `setUserInfo()` to update the current user.
* The reply tells you whether the login worked, not whether linking the user to this device worked.

**Response:**

| Situation                           | `success` | `error`                                                 |
| ----------------------------------- | --------- | ------------------------------------------------------- |
| Logged in                           | `true`    | —                                                       |
| A user is already logged in         | `false`   | `"User is already logged in"`                           |
| No `externalUserId` (or `userId`)   | `false`   | `"Session not created."` (iOS: `"session not created"`) |
| Empty payload                       | `false`   | —                                                       |
| Payload could not be read (Android) | `false`   | The parse error                                         |

### Set User Info

Updates the logged-in user: only the fields you pass change. Requires an earlier `login()`. Without `externalUserId` / `userId` or `email`, the session's values are used, so you can update only `meta`.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.User.setUserInfo({
  email: "new@b.com",
  meta: { plan: "pro" },
  syncWithNotification: true,
  callback: function (data) {
    console.log(data.success);
  },
});
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { setUserInfo } from "webtonative/User";

setUserInfo({
  email: "new@b.com",
  meta: { plan: "pro" },
  syncWithNotification: true,
  callback: (data) => {
    console.log(data.success);
  },
});
```

{% endtab %}
{% endtabs %}

**Callback Response:**

| Situation                 | `success`                        | `error`                              |
| ------------------------- | -------------------------------- | ------------------------------------ |
| Updated                   | `true`                           | —                                    |
| Not logged in             | `false`                          | `"Customer must call login() first"` |
| Empty payload             | iOS: `false` · Android: no reply | —                                    |
| Payload could not be read | Android: no reply                | —                                    |

The reply tells you whether the update worked, not whether linking to this device worked.

### Logout

Clears the session, unlinks the user from this device (including an id set with `setExternalUserId`), and reloads the page. No arguments, no reply. The device stays registered and keeps receiving notifications, but no longer as that user. Logout completes even offline.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.User.logout();
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { logout } from "webtonative/User";

logout();
```

{% endtab %}
{% endtabs %}

### Get User Info

Reads the current session without changing anything. The reply is the session object (with a `sessionVersion` field); the `token` field is removed. When nobody is logged in, iOS sends no reply.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.User.getUserInfo({
  callback: function (session) {
    console.log(session.externalUserId, session.email);
  },
});
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { getUserInfo } from "webtonative/User";

getUserInfo({
  callback: (session) => {
    console.log(session.externalUserId, session.email);
  },
});
```

{% endtab %}
{% endtabs %}

***

## Complete Example

A typical integration: a notifications toggle on a settings page, a user linked at sign-in, and tags kept in sync with the user's plan. Replace the `// your code` placeholders with your own UI and business logic.

```html
<label>
  <input type="checkbox" id="notif-toggle" disabled />
  Push notifications
</label>

<script>
  var toggle = document.getElementById("notif-toggle");

  // 1. Show the current subscription state
  window.WTN.Notification.isSubscribed()
    .then(function (response) {
      if (!response.success) {
        // Couldn't check. Your code: e.g. show "Try again later".
        return;
      }
      toggle.checked = response.status === "SUBSCRIBED";
      toggle.disabled = false;
    })
    .catch(function () {
      // Not running inside a WebToNative app. Your code: e.g. hide the toggle.
    });

  // 2. Subscribe / unsubscribe when the user flips the toggle
  toggle.addEventListener("change", function () {
    var wantOn = toggle.checked;
    toggle.disabled = true;

    var call = wantOn
      ? window.WTN.Notification.subscribe() // asks for the permission if needed
      : window.WTN.Notification.unsubscribe();

    call
      .then(function (response) {
        if (!response.success) {
          toggle.checked = !wantOn; // revert
          // Your code: e.g. "Couldn't update notifications. Check Settings or try again."
        }
      })
      .catch(function () {
        toggle.checked = !wantOn;
      })
      .finally(function () {
        toggle.disabled = false;
      });
  });

  // 3. After your own sign-in succeeds: link the user and save targeting tags
  function onSignedIn(user) {
    window.WTN.User.login(
      {
        externalUserId: user.id,
        email: user.email,
        name: user.name,
        meta: { plan: user.plan },
      },
      { syncWithNotification: true }
    ).then(function (response) {
      if (!response.success && response.error === "User is already logged in") {
        // A previous session is still active: update it instead
        window.WTN.User.setUserInfo({
          externalUserId: user.id,
          email: user.email,
          meta: { plan: user.plan },
        });
      }
    });

    window.WTN.Notification.setTag({ plan: user.plan, city: user.city })
      .then(function (response) {
        if (!response.success) {
          // Your code: e.g. retry later
        }
      })
      .catch(function (error) {
        console.error(error); // "data is required" if no tags were passed
      });
  }

  // 4. On sign-out: remove the user's tags, then unlink the user and clear the session (the page reloads)
  function onSignedOut() {
    window.WTN.Notification.removeTag(["plan", "city"])
      .catch(function () {})
      .finally(function () {
        window.WTN.User.logout();
      });
  }
</script>
```

***

## Reply Summary

| Function                              | Replies with | Keys                                                  | `success: true` means                         |
| ------------------------------------- | ------------ | ----------------------------------------------------- | --------------------------------------------- |
| `Notification.subscribe()`            | promise      | `success`                                             | Device subscribed                             |
| `Notification.unsubscribe()`          | promise      | `success`                                             | Device unsubscribed                           |
| `Notification.isSubscribed()`         | promise      | `success`; `status` when `true`; `error` when `false` | Check completed. Read `status` for the answer |
| `Notification.setTag()`               | promise      | `success`                                             | Tags saved                                    |
| `Notification.getTags()`              | promise      | `success`; `tags` when `true`                         | Tags read                                     |
| `Notification.removeTag()`            | promise      | `success`                                             | Tags removed                                  |
| `Notification.setExternalUserId()`    | promise      | `success`                                             | Request completed                             |
| `Notification.removeExternalUserId()` | promise      | `success` (always `true`)                             | User unlinked and session logged out          |
| `Permission.request()`                | promise      | `status`                                              | —                                             |
| `Permission.check()`                  | promise      | `permissionStatus`                                    | —                                             |
| `Permission.open()`                   | none         | —                                                     | —                                             |
| `User.login()`                        | promise      | `success`; `error` on most failures                   | Logged in                                     |
| `User.setUserInfo()`                  | callback     | `success`; `error` when not logged in                 | Updated                                       |
| `User.logout()`                       | none         | —                                                     | —                                             |
| `User.getUserInfo()`                  | callback     | session fields, `sessionVersion`                      | —                                             |

***

**Notes:**

* Always check `response.success`: the `WTN.Notification` promises resolve on failure too.
* For `isSubscribed`, `success` only says the check completed. Use `status` to decide whether the device is subscribed.
* Pass `removeTag` an array, even for one key.
* `removeExternalUserId()` logs the user out and reloads the page. To change which user the device belongs to without logging out, call `setExternalUserId()` with the new id.
