1.1.2 • Published 10 months ago

@iterable/web-sdk v1.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Iterable-Logo

Iterable's Web SDK

Iterable is a growth-marketing platform that helps you to create better experiences for—and deeper relationships with—your customers. Use it to send customized email, SMS, push notification, in-app message, embedded message, and web push notification campaigns to your customers.

This SDK helps you integrate your web apps with Iterable.

Table of contents

Other documentation

This document contains reference information about the Web SDK. For other information, please see:

Using the SDK

In general, to use the SDK, you'll need to follow these steps:

  1. In Iterable, create a JWT-enabled, web API key. The SDK can use this key to authenticate with Iterable's API endpoints. This will ensure the SDK has access to all the necessary. Save the API key and its associated JWT secret, since you'll need them both.

  2. Work with your Engineering team to create a web service the SDK can call to fetch a valid JWT token for the signed-in user. To learn more about how to do this, read JWT-Enabled API Keys.

  3. Install the SDK in your web app.

  4. Use the API key to initialize the SDK, as described in initialize and initializeWithConfig. When you initialize the SDK, pass in a method that can call the web service (created in step 2) to fetch a valid JWT token for the signed-in user.

  5. To identify the user to the SDK, call setEmail or setUserID (returned by initialize or initializeWithConfig). The SDK uses the user's email or userId to fetch a valid JWT token from your server.

  6. After the SDK successfully sets the user's email or userId and the SDK fetches a JWT token, you can make API requests to Iterable. For example, you can call track to track events, or getInAppMessages to fetch in-app messages, etc. Other methods are described below.

Installation

To install the SDK, use Yarn, npm, or a script tag:

  • npm

    npm install @iterable/web-sdk
  • Yarn

    yarn add @iterable/web-sdk
  • script tag

    <script src="https://unpkg.com/@iterable/web-sdk/index.js"></script>

Functions

Iterable's Web SDK exposes the following functions, which you can use in your website code.

For information about the data the SDK sends and receives when making calls to Iterable's API, see the API Overview.

Method NameDescription
filterHiddenInAppMessagesFrom an array of passed-in in-app messages, filters out messages that have already been read, messages that should not be displayed, and messages that only contain JSON data.
filterOnlyReadAndNeverTriggerMessagesFrom an array of passed-in in-app messages, filters out messages that have already been read and messages that should not be displayed.
getInAppMessagesFetches in-app messages by calling GET /api/inApp/getMessages.
initializeInitializes the SDK with an API key and a JWT refresh method. Returns methods you can use to identify the current user, work with JWT tokens, and log the user out (see WithJWT).
initializeWithConfigSimilar to initialize, but also takes a set of configuration options as a parameter. Returns methods you can use to identify the current user, work with JWT tokens, and log the user out (see WithJWT).
IterableEmbeddedCardReturns a string of the HTML for an out-of-the-box card view for an embedded message.
IterableEmbeddedBannerReturns a string of the HTML for an out-of-the-box banner view for an embedded message.
IterableEmbeddedNotificationReturns a string of the HTML for an out-of-the-box notification view for an embedded message.
sortInAppMessagesSorts an array of in-app messages by priority, and then creation date.
trackTracks a custom event by calling POST /api/events/track.
trackEmbeddedClickTracks an embeddedClick event by calling POST /api/embedded-messaging/events/click.
trackEmbeddedReceivedTracks an embeddedReceived event by calling POST /api/embedded-messaging/events/received.
trackEmbeddedSessionTracks an embeddedSession event and related embeddedImpression events by calling POST /api/embedded-messaging/events/session.
trackInAppClickTracks an inAppClick event by calling POST /api/events/trackInAppClick.
trackInAppCloseTracks an inAppClose event by calling POST /api/events/trackInAppClose.
trackInAppConsumeDeletes an in-app message from the server by calling POST /api/events/trackInAppConsume.
trackInAppDeliveryTracks an inAppDelivery event by calling POST /api/events/trackInAppDelivery.
trackInAppOpenTracks an inAppOpen event by calling POST /api/events/trackInAppOpen.
trackPurchaseTracks a purchase event by calling POST /api/commerce/trackPurchase.
updateCartUpdates the shopping cart items on the user's Iterable profile by calling POST /api/commerce/updateCart.
updateSubscriptionsUpdates the user's subscriptions by calling POST /api/users/updateSubscriptions.
updateUserUpdates the data on a user's Iterable profile by calling POST /api/users/updateUser.
updateUserEmailUpdates the current user's email by calling POST /api/users/updateEmail. Causes the SDK to fetch a JWT for the new email address.

Notes:

  • The SDK does not track inAppDelete events.

  • :rotating_light: Due to a limitation in WebKit (which affects iOS web browsers, like Safari), in-app messages displayed in an iOS web browser browser can't automatically track inAppClick events or handle custom CTAs. This will impact analytics for all Safari and mobile iOS users.

filterHiddenInAppMessages

From an array of passed-in in-app messages, filters out messages that have already been read, messages that should not be displayed, and messages that only contain JSON data.

const filterHiddenInAppMessages = (
  messages: Partial<InAppMessage>[] = []
): Partial<InAppMessage>[]

See also:

filterOnlyReadAndNeverTriggerMessages

From an array of passed-in in-app messages, filters out messages that have already been read and messages that should not be displayed.

const filterOnlyReadAndNeverTriggerMessages = (
  messages: Partial<InAppMessage>[] = []
): Partial<InAppMessage>[]

See also:

getInAppMessages

Fetches in-app messages by calling GET /api/inApp/getMessages.

// Returns a promise that resolves to an InAppMessageResponse, which has an
// array of fetched in-app messages.
function getInAppMessages(
  payload: InAppMessagesRequestParams
): IterablePromise<InAppMessageResponse>;

// Returns methods to request messages from the server, pause message display, 
// restart message display, and trigger the display of a message.
function getInAppMessages(
  payload: InAppMessagesRequestParams,
  options: {
    display: DisplayOptions;
  }
): GetInAppMessagesResponse

payload options (see InAppMessagesRequestParams):

Property NameDescriptionValueDefault
animationDurationHow long (in ms) it should take messages to animate in and outnumber400
bottomOffsetHow much space (px or %) to create between the bottom of the screen and a message. Not applicable for center, top, or full-screen messages.stringundefined
closeButtonProperties that define a custom close button to display on a message.CloseButtonOptions (see below)undefined
displayIntervalHow long (in ms) to wait before showing the next in-app message after closing the currently open onenumber30000
handleLinksHow to open links. If undefined, use browser-default behavior. open-all-new-tab opens all in new tab, open-all-same-tab opens all in same tab, external-new-tab opens only off-site links in new tab, otherwise same tab. Overrides the target attribute defined on link elements.'open-all-new-tab' \| 'open-all-same-tab' \| 'external-new-tab'undefined
onOpenNodeToTakeFocusThe DOM element that should receive keyboard focus when the in-app message opens. Any query selector is valid. If not specified, the first interactive element receives focus.stringundefined
onOpenScreenReaderMessageThe text a screen reader should read when opening the message.stringundefined
rightOffsetThe amount of space (px or %) to create between the right of the screen and the message. Not applicable for center or full-screen messages.stringundefined
topOffsetHow much space (px or %) to create between the top of the screen and a message. Not applicable for center, bottom, or full-screen messages.stringundefined

closeButton options (see CloseButton):

Property NameDescriptionValueDefault
colorThe button's color (does not affect custom icons)stringundefined
iconPathCustom pathname to an image or SVG to use (instead of the default "X")stringundefined
isRequiredToDismissMessageIf true, users cannot dismiss in-app messages by clicking outside of them.booleanundefined
positionWhere the button should display on an in-app message'top-right' \| 'top-left''top-right'
sideOffsetHow much space to leave between the button and side of the containerstring'4%'
sizeHow large to set the width, height, and font-sizestring \| number24
topOffsetHow much space to leave between the button and the top of the containerstring'4%'

Example:

import { getInAppMessages } from '@iterable/web-sdk';

getInAppMessages({ count: 20, packageName: 'mySite1' })
  .then((resp) => {
    // This is an iframe element that can be attached to the DOM 
    const messageIframe = resp.data.inAppMessages[0].content.html;
    document.body.appendChild(messageIframe);
    // Additional styling logic can be done here to render the message in a 
    // custom way
  })
  .catch();

This code, which doesn't include the options parameter, fetches in-app messages from Iterable and places the first one on the page. However, it won't be visible. To render it, modify the page's CSS to display the message as necessary. You'll also need to set up click handlers to handle click events, close the message, etc.

Here's some example code that shows messages automatically:

import { getInAppMessages } from '@iterable/web-sdk';

const { request, pauseMessageStream, resumeMessageStream } = getInAppMessages(
  {
    count: 20,
    packageName: 'my-website',
    displayInterval: 5000,
    onOpenScreenReaderMessage:
      'The screen reader will read this',
    onOpenNodeToTakeFocus: 'input',
    closeButton: {
      color: 'red',
      size: '16px',
      topOffset: '20px'
    }
  },
  { display: 'immediate' }
);

request().then().catch();

This example uses custom sorting and filtering, and displays messages at the app's discretion:

import {
  getInAppMessages,
  sortInAppMessages,
  filterHiddenInAppMessages
} from '@iterable/web-sdk';

const {
  request,
  pauseMessageStream,
  resumeMessageStream,
  triggerDisplayMessages
} = getInAppMessages(
  {
    count: 20,
    packageName: 'my-website',
    displayInterval: 5000,
    onOpenScreenReaderMessage: 'The screen reader will read this',
    onOpenNodeToTakeFocus: 'input',
    closeButton: {
      color: 'red',
      size: '16px',
      topOffset: '20px'
    }
  },
  { display: 'deferred' }
);

request()
  .then((response) => {
    // Do your own manipulation here 
    const filteredMessages = yourOwnSortingAndFiltering(response.data.inAppMessages);

    // Or, feel free to take advantage of the sorting/filtering methods used 
    // internally
    const furtherManipulatedMessages = sortInAppMessages(
      filterHiddenInAppMessages(response.data.inAppMessages)
    ) as InAppMessage[];

    // Then display them whenever you want
    triggerDisplayMessages(furtherManipulatedMessages);
  })
  .catch();

:rotating_light: With the deferred option, the SDK does not filter or sort the messages. The messages come back exactly as retrieved from the API, without modification. This means that you may (for example) show in-app messages marked as read, or show messages in the default order (based on priority), rather than a custom order that you control.

In this case, to apply the SDK's default sorting and filtering, use the sortInAppMessages and filterHiddenInAppMessages methods. Also, see filterOnlyReadAndNeverTriggerMessages, which is similar to filterHiddenInAppMessages but does not filter out JSON-only messages.

Notes:

  • :rotating_light: v1.0.0 of this SDK removes support for showMessagesAutomatically?: boolean. If needed, please update your getInAppMessages requests to use options: { display: 'deferred' | 'immediate' }.

See also:

initialize

Initializes the SDK with an API key and a JWT refresh method. Returns methods you can use to identify the current user, work with JWT tokens, and log the user out (see WithJWT).

function initialize(
  authToken: string,
  generateJWT: (payload: GenerateJWTPayload) => Promise<string>
): WithJWT;

generateJWT should be a function that takes a userId or email and uses it to fetch, from your server, a valid JWT token for that user. The function should return the token as a string.

Example:

import { initialize } from '@iterable/web-sdk';

const { clearRefresh, setEmail, setUserID, logout } = initialize(
  '<YOUR_API_KEY>',
  // email will be defined if you call setEmail 
  // userID_ will be defined if you call setUserID
  ({ email, userID }) =>
    yourAsyncJWTGeneratorMethod({ email, userID }).then(
      ({ jwt_token }) => jwt_token
    )
);

See also:

initializeWithConfig

Similar to initialize, but also takes a set of configuration options as a parameter. Returns methods you can use to identify the current user, work with JWT tokens, and log the user out (see WithJWT).

The configuration options you can pass to this function are useful if you need to point the SDK to Iterable's EU API endpoints or allow JavaScript execution in Safari tabs.

function initializeWithConfig(initializeParams: WithJWTParams): WithJWT;

Example:

import { initializeWithConfig } from '@iterable/web-sdk';

const { clearRefresh, setEmail, setUserID, logout } = initializeWithConfig({
  authToken: '<YOUR_API_KEY>',
  configOptions: {
    isEuIterableService: false,
    dangerouslyAllowJsPopups: true,
  },
  
  // email will be defined if you call setEmail
  // userID will be defined if you call setUserID
  generateJWT: ({ email, userID }) =>
    yourAsyncJWTGeneratorMethod({ email, userID }).then(
      ({ jwt_token }) => jwt_token
    )
}
);

generateJWT should be a function that takes a userId or email and uses it to fetch, from your server, a valid JWT token for that user. The function should return the token as a string.

See also:

IterableEmbeddedCard

Returns a string of the HTML for an out-of-the-box card view for an embedded message.

const emptyElement = {
  id: '',
  styles: ''
};

function IterableEmbeddedCard({
  appPackageName,
  message,
  htmlElements = {
    parent: emptyElement,
    img: emptyElement,
    title: emptyElement,
    primaryButton: emptyElement,
    secondaryButton: emptyElement,
    body: emptyElement,
    buttonsDiv: emptyElement,
    textTitle: emptyElement
  },
  errorCallback
}: OOTB): string

Parameters:

  • appPackageName – The package name you use to identify your website to Iterable's Web SDK.
  • message – The IterableEmbeddedMessage object that represents the message you want to display.
  • htmlElements – Custom styles (type Elements) for the SDK to use when displaying the embedded message. For details, see Custom Styles.
  • errorCallback – A callback that the SDK calls if it encounters an error when tracking embeddedClick events.
import { IterableEmbeddedCard } from '@iterable/web-sdk';

const card = IterableEmbeddedCard({
  packageName,
  message,
  htmlElements,
  errorCallback: (error) => console.log('handleError: ', error)
});

To display the message, set the innerHTML of an HTML element to the string returned by IterableEmbeddedCard.

For more info, see:

Also see:

IterableEmbeddedBanner

Returns a string of the HTML for an out-of-the-box banner view for an embedded message.

function IterableEmbeddedBanner({
  appPackageName,
  message,
  htmlElements = {
    parent: emptyElement,
    img: emptyElement,
    title: emptyElement,
    primaryButton: emptyElement,
    secondaryButton: emptyElement,
    body: emptyElement,
    buttonsDiv: emptyElement,
    textTitle: emptyElement,
    textTitleImg: emptyElement
  },
  errorCallback
}: OOTB): string 

Parameters:

  • appPackageName – The package name you use to identify your website to Iterable's Web SDK.
  • message – The IterableEmbeddedMessage object that represents the message you want to display.
  • htmlElements – Custom styles (type Elements) for the SDK to use when displaying the embedded message. For details, see Custom Styles.
  • errorCallback – A callback that the SDK calls if it encounters an error when tracking embeddedClick events.

For example:

import { IterableEmbeddedBanner } from '@iterable/web-sdk';

const banner = IterableEmbeddedBanner({
  packageName,
  message,
  htmlElements,
  errorCallback: (error) => console.log('handleError: ', error)
});

To display the message, set the innerHTML of an HTML element to the string returned by IterableEmbeddedBanner.

For more info, see:

Also see:

IterableEmbeddedNotification

Returns a string of the HTML for an out-of-the-box notification view for an embedded message.

function IterableEmbeddedNotification({
  appPackageName,
  message,
  htmlElements = {
    parent: emptyElement,
    title: emptyElement,
    primaryButton: emptyElement,
    secondaryButton: emptyElement,
    body: emptyElement,
    buttonsDiv: emptyElement,
    textTitle: emptyElement
  },
  errorCallback
}: OOTB): string

Parameters:

  • appPackageName – The package name you use to identify your website to Iterable's Web SDK.
  • message – The IterableEmbeddedMessage object that represents the message you want to display.
  • htmlElements – Custom styles (type Elements) for the SDK to use when displaying the embedded message. For details, see Custom Styles.
  • errorCallback – A callback that the SDK calls if it encounters an error when tracking embeddedClick events.
import { IterableEmbeddedNotification } from '@iterable/web-sdk';

const notification = IterableEmbeddedNotification({
  packageName,
  message,
  htmlElements,
  errorCallback: (error) => console.log('handleError: ', error)
});

To display the message, set the innerHTML of an HTML element to the string returned by IterableEmbeddedNotification.

For more info, see:

Also see:

sortInAppMessages

Sorts an array of in-app messages by priority, and then creation date.

const sortInAppMessages = (messages: Partial<InAppMessage>[] = []) => {
  return messages.sort(by(['priorityLevel', 'asc'], ['createdAt', 'asc']));
};

In-app messages can have these priority values:

  • Low - priorityLevel of 400.5
  • Medium - priorityLevel of 300.5
  • High - priorityLevel of 200.5
  • Critical - priorityLevel of 100.5
  • Proof - priorityLevel of 100.0

Also see:

track

Tracks a custom event by calling POST /api/events/track.

track: (payload: InAppTrackRequestParams): IterablePromise<IterableResponse>

Example:

import { track } from '@iterable/web-sdk';

track({ eventName: 'my-event' }).then().catch();

See also:

trackEmbeddedClick

Tracks an embeddedClick event by calling POST /api/embedded-messaging/events/click.

const trackEmbeddedClick = (
  payload: IterableEmbeddedClickRequestPayload
): IterablePromise<IterableResponse>

Example:

import { trackEmbeddedReceived } from '@iterable/web-sdk';

trackEmbeddedClick({
  messageId: message.metadata.messageId, 
  buttonIdentifier: button.id,
  clickedUrl: defaultUrl,
  appPackageName: packageName
}).then((response) => {
  if (response.status != 200) {
    console.log("Failure tracking embedded click")
  }
}).catch((error) => {
  console.log("Error tracking embedded click: ", error);
});

See also:

trackEmbeddedReceived

Tracks an embeddedReceived event by calling POST /api/embedded-messaging/events/received.

Generally, there's no need to call this method, since the SDK automatically tracks an embeddedReceived event for each message it fetches from the server.

const trackEmbeddedReceived = (
  messageId: string,
  appPackageName: string
): IterablePromise<IterableResponse>

Example:

import { trackEmbeddedReceived } from '@iterable/web-sdk';

trackEmbeddedReceived(messageId, packageName)
  .then((response: any) => {
    setTrackResponse(JSON.stringify(response.data));
    setTrackingEvent(false);
  })
  .catch((error: any) => {
    setTrackResponse(JSON.stringify(error.response.data));
    setTrackingEvent(false);
  });

See also:

trackEmbeddedSession

Tracks an embeddedSession event and related embeddedImpression events by calling POST /api/embedded-messaging/events/session.

Generally, rather than calling this method, you'll track sessions and impresions using the SDK's IterableEmbeddedSessionManager.

const trackEmbeddedSession = (
  payload: IterableEmbeddedSessionRequestPayload
): IterablePromise<IterableResponse>

Example:

import { trackEmbeddedSession } from '@iterable/web-sdk';

trackEmbeddedSession(sessionData)
  .then((response: any) => {
    setTrackResponse(JSON.stringify(response.data));
    setTrackingEvent(false);
  })
  .catch((error: any) => {
    setTrackResponse(JSON.stringify(error.response.data));
    setTrackingEvent(false);
  });

See also:

trackInAppClick

Tracks an inAppClick event by calling POST /api/events/trackInAppClick.

const trackInAppClick = (
  payload: Omit<InAppEventRequestParams, 'inboxSessionId' | 'closeAction'>,
  sendBeacon = false
): IterablePromise<IterableResponse>

Example:

import { trackInAppClick } from '@iterable/web-sdk';

trackInAppClick({
  messageId: '123',
  deviceInfo: { appPackageName: 'my-website' }
})
  .then()
  .catch();

See also:

trackInAppClose

Tracks an inAppClose event by calling POST /api/events/trackInAppClose.

const trackInAppClose = (payload: InAppEventRequestParams): IterablePromise<IterableResponse>

Example:

import { trackInAppClose } from '@iterable/web-sdk';

trackInAppClose({
  messageId: '123',
  deviceInfo: { appPackageName: 'my-website' }
})
  .then()
  .catch();

See also:

trackInAppConsume

Deletes an in-app message from the server by calling POST /api/events/trackInAppConsume.

const trackInAppConsume = (
  payload: Omit<
    InAppEventRequestParams,
    'clickedUrl' | 'closeAction' | 'inboxSessionId'
  >
): IterablePromise<IterableResponse>

Example:

import { trackInAppConsume } from '@iterable/web-sdk';

trackInAppConsume({
  messageId: '123',
  deviceInfo: { appPackageName: 'my-website' }
})
  .then()
  .catch();

See also:

trackInAppDelivery

Tracks an inAppDelivery event by calling POST /api/events/trackInAppDelivery.

const trackInAppDelivery = (
  payload: Omit<
    InAppEventRequestParams,
    'clickedUrl' | 'closeAction' | 'inboxSessionId'
  >
): IterablePromise<IterableResponse>

Example:

import { trackInAppDelivery } from '@iterable/web-sdk';

trackInAppDelivery({
  messageId: '123',
  deviceInfo: { appPackageName: 'my-website' }
})
  .then()
  .catch();

See also:

trackInAppOpen

Tracks an inAppOpen event by calling POST /api/events/trackInAppOpen.

const trackInAppOpen = (
  payload: Omit<
    InAppEventRequestParams,
    'clickedUrl' | 'inboxSessionId' | 'closeAction'
  >
): IterablePromise<IterableResponse>

Example:

import { trackInAppOpen } from '@iterable/web-sdk';

trackInAppOpen({
  messageId: '123',
  deviceInfo: { appPackageName: 'my-website' }
})
  .then()
  .catch();

See also:

trackPurchase

Tracks a purchase event by calling POST /api/commerce/trackPurchase.

const trackPurchase = (payload: TrackPurchaseRequestParams): IterablePromise<IterableResponse>

Example:

import { trackPurchase } from '@iterable/web-sdk';

trackPurchase({
  items: [{ id: '123', name: 'keyboard', price: 100, quantity: 2 }],
  total: 200
})
  .then()
  .catch();

See also:

updateCart

Updates the shopping cart items on the user's Iterable profile by calling POST /api/commerce/updateCart.

const updateCart = (payload: UpdateCartRequestParams): IterablePromise<IterableResponse>

Example:

import { updateCart } from '@iterable/web-sdk';

updateCart({
  items: [{ id: '123', price: 100, name: 'keyboard', quantity: 1 }]
})
  .then()
  .catch();

See also:

updateSubscriptions

Updates the user's subscriptions by calling POST /api/users/updateSubscriptions.

const updateSubscriptions = (
  payload: Partial<UpdateSubscriptionParams> = {}
): IterablePromise<IterableResponse>

Example:

import { updateSubscriptions } from '@iterable/web-sdk';

updateSubscriptions({ emailListIds: [1, 2, 3] })
  .then()
  .catch();

See also:

updateUser

Updates the data on a user's Iterable profile by calling POST /api/users/updateUser.

const updateUser = (payload: UpdateUserParams = {}): IterablePromise<IterableResponse>

Example:

import { updateUser } from '@iterable/web-sdk';

updateUser({ dataFields: {} }).then().catch();

See also:

updateUserEmail

Updates the current user's email by calling POST /api/users/updateEmail. Causes the SDK to fetch a JWT for the new email address.

updateUserEmail: (newEmail: string): IterablePromise<IterableResponse>

Example:

import { updateUserEmail } from '@iterable/web-sdk';

updateUserEmail('user@example.com').then().catch();

See also:

Classes, interfaces, types, and enums

This section describes classes, interfaces, and enums to be aware of when working with Embedded Messaging in Iterable's Web SDK.

TypeDescription
CloseButtonSpecifies how the SDK should display a close button on the associated in-app message. Passed as part of InAppMessagesRequestParams.
CloseButtonPositionSpecifies the position of the close button on the associated in-app message.
CommerceItemAn item being purchased or added to a shopping cart. Include when calling trackPurchase or updateCart.
CommerceUserInformation about the user associated with a purchase or cart update. Include when calling trackPurchase or updateCart.
DisplayOptionsDisplay options to pass to getInAppMessages to indicate whether messages should be displayed immediately or later.
DisplayPositionDescribes where an in-app message should be displayed. Part of WebInAppDisplaySettings.
ElementsCustom styles to apply to IterableEmbeddedCard, IterableEmbeddedBanner, and IterableEmbeddedNotification views for embedded messages.
GenerateJWTPayloadThe payload to pass to the generateJWT function when calling initialize or initializeWithConfig.
ErrorHandlerAn error-handling function. Passed as a parameter to IterableEmbeddedCard, IterableEmbeddedBanner, and IterableEmbeddedNotification, which use the method to handle errors when tracking embeddedClick events.
GetInAppMessagesResponseReturn value for getInAppMessages, when it's called without the options parameter.
HandleLinksDescribes where in-app links should be opened. Part of InAppMessagesRequestParams.
InAppMessageA single in-app message.
InAppDisplaySettingDisplay settings for an in-app message, including padding percentages.
InAppEventRequestParamsData to pass to trackInAppClick, trackInAppClose, trackInAppConsume, trackInAppDelivery, and trackInAppOpen.
InAppMessagesRequestParamsData to pass to getInAppMessages.
InAppMessageResponseReturn value for getInAppMessages, when it's called with the options parameter.
InAppTrackRequestParamsData to pass to track.
IterableActionAn action associated with a click. The type of the action, and its associated URL.
IterableActionContextInformation about the context of an IterableAction. For example, the associated message type. Only used with embedded messages.
IterableActionSourceAn enum of possible message types to which an IterableAction can be associated. Currently, only EMBEDDED is supported.
IterableConfigA class that can hold configuration information for the SDK. Currently, only urlHandler and customActionHandler are supported (static properties), and these are only invoked for URLs and custom actions coming from embedded messages.
IterableCustomActionHandlerAn interface that defines handleIterableCustomAction, which the SDK can call to handle custom action URLs (action://) URLs that result from from clicks on embedded messages.
IterableEmbeddedButtonPayload for a button associated with an embedded message.
IterableEmbeddedButtonActionPayload for the action associated with an embedded message button.
IterableEmbeddedClickRequestPayloadData to pass to trackEmbeddedClick.
IterableEmbeddedDefaultActionThe default action associated with an embedded message. Invoked when a user clicks on an embedded message, but outside of its buttons.
IterableEmbeddedElementsContent associated with an embedded message — title, body, media URL, buttons, default action, and extra text fields.
IterableEmbeddedImpressionThe number of times a given embedded message appeared during a specific session, and the total duration of all those appearances. Also includes other metadata about the impression.
IterableEmbeddedManagerUsed to fetch embedded messages from Iterable, and pass them to application code as necessary.
IterableEmbeddedMessageA single embedded message to display, including title text, body text, buttons, an image URL, click actions, text fields, and JSON data.
IterableEmbeddedMessageUpdateHandlerAn object that defines onMessagesUpdated and onEmbeddedMessagingDisabled methods. If this object is registered as an update listener for embedded messages (you can do this by calling addUpdateListener on IterableEmbeddedManager), the SDK calls these methods as necessary after fetching embedded messages from the server.
IterableEmbeddedMetadataIdentifying information about an embedded message.
IterableEmbeddedSessionRepresents a period of time during which a user was on a page where they could potentially view embedded messages. Contains an ID, a start time, and an end time.
IterableEmbeddedSessionManagerUsed to track sessions and impressions, and to save them back to Iterable.
IterableEmbeddedSessionRequestPayloadData to pass to trackEmbeddedSession. You won't usually interact manually with this interface, since the IterableEmbeddedSessionManager handles the tracking of sessions and impressions for you.
IterableEmbeddedTextExtra text fields sent along with an embedded message. Like custom JSON, these text fields can be used to pass data as part of an embedded message.
IterableErrorStatusErrors that can come back with an IterableResponse.
IterablePromiseA promise.
IterableResponseA response from Iterable's API.
IterableUrlHandlerAn interface that defines handleIterableURL, which the SDK can call to handle standard URLs (https://, custom://, but not action://) that result from from clicks on embedded messages.
OOTBA type that defines the parameters to provide when calling IterableEmbeddedCard, IterableEmbeddedBanner, and IterableEmbeddedNotification.
OptionsConfiguration options to pass to initializeWithConfig.
OutOfTheBoxButtonCustom styles to apply to buttons in an embedded message. The same as OutOfTheBoxElement, but with an extra disabledStyles string.
OutOfTheBoxElementThe custom styles to apply to a single element of an embedded message.
SDKInAppMessagesParamsParent interface for InAppMessagesRequestParams.
TrackPurchaseRequestParamsParameters to pass to trackPurchase.
UpdateCartRequestParamsData to pass to updateCart.
UpdateSubscriptionParamsData to pass to updateSubscriptions.
UpdateUserParamsData to pass to updateUser.
WebInAppDisplaySettingsAn object that contains information about how to display the associated in-app message.
WithJWTReturn value from initialize and initializeWithConfig.
WithJWTParamsParameters to pass to initializeWithConfig.

CloseButton

Specifies how the SDK should display a close button on the associated in-app message. Passed as part of InAppMessagesRequestParams.

type CloseButton = {
    color?: string;
    iconPath?: string;
    // If true, prevent user from dismissing in-app message by clicking outside 
    // of message
    isRequiredToDismissMessage?: boolean;
    position?: CloseButtonPosition;
    sideOffset?: string;
    size?: string | number;
    topOffset?: string;
};

See also:

CloseButtonPosition

Specifies the position of the close button on the associated in-app message.

declare enum CloseButtonPosition {
    TopLeft = "top-left",
    TopRight = "top-right"
}

CommerceItem

An item being purchased or added to a shopping cart. Include when calling trackPurchase or updateCart.

interface CommerceItem {
  id: string;
  sku?: string;
  name: string;
  description?: string;
  categories?: string[];
  price: number;
  quantity: number;
  imageUrl?: string;
  url?: string;
  dataFields?: Record<string, any>;
}

CommerceUser

Information about the user associated with a purchase or cart update. Include when calling trackPurchase or updateCart.

interface CommerceUser {
  dataFields?: Record<string, any>;
  preferUserId?: boolean;
  mergeNestedObjects?: boolean;
}

DisplayOptions

Display options to pass to getInAppMessages to indicate whether messages should be displayed immediately or later.

declare enum DisplayOptions {
    Immediate = "immediate",
    Deferred = "deferred"
}

DisplayPosition

Describes where an in-app message should be displayed. Part of WebInAppDisplaySettings.

declare enum DisplayPosition {
    Center = "Center",
    TopRight = "TopRight",
    BottomRight = "BottomRight",
    Full = "Full"
}

See also:

Elements

Custom styles to apply to IterableEmbeddedCard, IterableEmbeddedBanner, and IterableEmbeddedNotification views for embedded messages.

type Elements = {
  // img div
  img?: OutOfTheBoxElement;
  // title div
  title?: OutOfTheBoxElement;
  // primary button div
  primaryButton?: OutOfTheBoxButton;
  // secondary button div
  secondaryButton?: OutOfTheBoxButton;
  // body button div
  body?: OutOfTheBoxElement;
  // root OOTB div
  parent?: OutOfTheBoxElement;
  // button wrapper div
  buttonsDiv?: OutOfTheBoxElement;
  // title and parent wrapper div
  textTitle?: OutOfTheBoxElement;
  // textTitleImg div
  textTitleImg?: OutOfTheBoxElement;
};

See also:

GenerateJWTPayload

The payload to pass to the generateJWT function when calling initialize or initializeWithConfig.

interface GenerateJWTPayload {
  email?: string;
  userID?: string;
}

ErrorHandler

An error-handling function. Passed as a parameter to IterableEmbeddedCard, IterableEmbeddedBanner, and IterableEmbeddedNotification, which use the method to handle errors when tracking embeddedClick events.

interface ErrorHandler {
  (error: any): void;
}

GetInAppMessagesResponse

Return value for getInAppMessages, when it's called without the options parameter.

interface GetInAppMessagesResponse {
  pauseMessageStream: () => void;
  resumeMessageStream: () => Promise<HTMLIFrameElement | ''>;
  request: () => IterablePromise<InAppMessageResponse>;
  triggerDisplayMessages: (
    messages: Partial<InAppMessage>[]
  ) => Promise<HTMLIFrameElement | ''>;
}

HandleLinks

Describes where in-app links should be opened. Part of InAppMessagesRequestParams.

declare enum HandleLinks {
    OpenAllNewTab = "open-all-new-tab",
    OpenAllSameTab = "open-all-same-tab",
    ExternalNewTab = "external-new-tab"
}

InAppMessage

A single in-app message.

interface InAppMessage {
  messageId: string;
  campaignId: number;
  createdAt: number;
  expiresAt: number;
  content: {
    payload?: Record<string, any>;
    html: string | HTMLIFrameElement;
    inAppDisplaySettings: {
      top: InAppDisplaySetting;
      right: InAppDisplaySetting;
      left: InAppDisplaySetting;
      bottom: InAppDisplaySetting;
      bgColor?: {
        alpha: number;
        hex: string;
      };
      shouldAnimate?: boolean;
    };
    webInAppDisplaySettings: WebInAppDisplaySettings;
  };
  customPayload: Record<string, any>;
  trigger: {
    type: string;
  };
  saveToInbox: boolean;
  inboxMetadata: {
    title: string;
    subtitle: string;
    icon: string;
  };
  priorityLevel: number;
  read: boolean;
}

See also:

InAppDisplaySetting

Display settings for an in-app message, including padding percentages.

interface InAppDisplaySetting {
  percentage?: number;
  displayOption?: string;
}

InAppEventRequestParams

Data to pass to trackInAppClick, trackInAppClose, trackInAppConsume, trackInAppDelivery, and trackInAppOpen.

interface InAppEventRequestParams {
  messageId: string;
  clickedUrl?: string;
  messageContext?: {
    saveToInbox?: boolean;
    silentInbox?: boolean;
    location?: string;
  };
  closeAction?: string;
  deviceInfo: {
    appPackageName: string; 
  };
  inboxSessionId?: string;
  createdAt?: number;
}

InAppMessagesRequestParams

Data to pass to getInAppMessages.

interface InAppMessagesRequestParams extends SDKInAppMessagesParams {
    count: number;
    SDKVersion?: string;
    packageName: string;
}

See also:

InAppMessageResponse

Return value for getInAppMessages, when it's called with the options parameter.

interface InAppMessageResponse {
  inAppMessages: Partial<InAppMessage>[];
}

See also:

InAppTrackRequestParams

Data to pass to track.

interface InAppTrackRequestParams {
  eventName: string;
  id?: string;
  createdAt?: number;
  dataFields?: Record<string, any>;
  campaignId?: number;
  templateId?: number;
}

IterableAction

An action associated with a click. The type of the action, and its associated URL. Only used with embedded messages.

interface IterableAction {
  type: string;
  data: string;
}

The values for type and data depend on the type of action assigned to the campaign in Iterable:

  • For Open URL actions, type is openUrl and data contains the URL.
  • For Custom action actions, type is the URL, and data is empty.

IterableActionContext

Information about the context of an IterableAction. For example, the associated message type. Only used with embedded messages.

interface IterableActionContext {
  action: IterableAction;
  source: IterableActionSource;
}

See also:

IterableActionSource

An enum of possible message types to which an IterableAction can be associated. Currently, only EMBEDDED is supported.

enum IterableActionSource {
  EMBEDDED = 'EMBEDDED'
}

IterableConfig

A class that can hold configuration information for the SDK. Currently, only urlHandler and customActionHandler are supported (static properties), and these are only invoked for URLs and custom actions coming from embedded messages.

class IterableConfig {
  public static urlHandler: IterableUrlHandler | null = null;
  public static customActionHandler: IterableCustomActionHandler | null = null;
}

See also:

IterableCustomActionHandler

An interface that defines handleIterableCustomAction, which the SDK can call to handle custom action URLs (action://) URLs that result from from clicks on embedded messages.

interface IterableCustomActionHandler {
  handleIterableCustomAction(
    action: IterableAction,
    actionContext: IterableActionContext
  ): boolean;
}

See also:

IterableEmbeddedButton

Payload for a button associated with an embedded message.

interface IterableEmbeddedButton {
  id: string;
  title?: string;
  action?: IterableEmbeddedButtonAction;
}

See also:

IterableEmbeddedButtonAction

Payload for the action associated with an embedded message button.

interface IterableEmbeddedButtonAction {
  type: string;
  data?: string;
}

The values for type and data depend on the type of action assigned to the campaign in Iterable:

  • For Open URL actions, type is openUrl and data contains the URL.
  • For Custom action actions, type is the URL, and data is empty.

IterableEmbeddedClickRequestPayload

Data to pass to trackEmbeddedClick.

interface IterableEmbeddedClickRequestPayload {
  messageId: string;
  buttonIdentifier: string;
  targetUrl: string;
  appPackageName: string;
}

IterableEmbeddedDefaultAction

The default action associated with an embedded message. Invoked when a user clicks on an embedded message, but outside of its buttons.

interface IterableEmbeddedDefaultAction {
  type: string;
  data?: string;
}

The values for type and data depend on the type of action assigned to the campaign in Iterable:

  • For Open URL actions, type is openUrl and data contains the URL.
  • For Custom action actions, type is the URL, and data is empty.

IterableEmbeddedElements

Content associated with an embedded message — title, body, media URL, buttons, default action, and extra text fields.

interface IterableEmbeddedElements {
  title?: string;
  body?: string;
  mediaUrl?: string;
  buttons?: IterableEmbeddedButton[];
  text?: IterableEmbeddedText[];
  defaultAction?: IterableEmbeddedDefaultAction;
}

See also:

IterableEmbeddedImpression

The number of times a given embedded message appeared during a specific session, and the total duration of all those appearances. Also includes other metadata about the impression.

interface IterableEmbeddedImpression {
  messageId: string;
  displayCount: number;
  displayDuration: number;
  placementId?: number;
}

IterableEmbeddedManager

Used to fetch embedded messages from Iterable, and pass them to application code as necessary.

class IterableEmbeddedManager {
    appPackageName: string;
    constructor(appPackageName: string);
    syncMessages(packageName: string, callback: () => void, placementIds?: number[]): Promise<void>;
    getMessages(): IterableEmbeddedMessage[];
    getMessagesForPlacement(placementId: number): IterableEmbeddedMessage[];
    addUpdateListener(updateListener: IterableEmbeddedMessageUpdateHandler): void;
    getUpdateHandlers(): IterableEmbeddedMessageUpdateHandler[];
    click(clickedUrl: string | null): void;
}

Descriptions:

  • appPackageName – The package name you use to identify your website. Set this value by passing it to the constructror.

  • syncMessages – Fetches embedded messages for which the signed-in user is eligible. If placementIds is provided, fetches only messages for those placements. Calls callback after fetching messages.

  • getMessages – Returns all embedded messages that the SDK has already fetched. Does not fetch messages from the server.

  • getMessagesForPlacement – Returns all embedded messages for a given placement ID. Does not fetch messages from the server.

  • addUpdateListener – Registers an object that implements the IterableEmbeddedMessageUpdateHandler interface. The SDK calls the object's onMessagesUpdated and onEmbeddedMessagingDisabled methods as necessary after fetching embedded messages from the server.

  • getUpdateHandlers – Returns all objects that have been registered as update listeners.

  • click – Passes the provided URL (depending on its type) to the URL handler or custom action handler defined on IterableConfig. action:// URLs are passed to the custom action handler, and other URLs are passed to the URL handler. The SDK does not currently support iterable:// URLs for embedded messages.

See also:

1.1.2

10 months ago

1.1.1

12 months ago

1.1.0

1 year ago

1.0.11

1 year ago

1.0.10

1 year ago

1.1.1-beta

1 year ago

1.0.9

1 year ago

1.1.0-beta

1 year ago

1.0.8

1 year ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

3 years ago

0.4.1

3 years ago

0.4.0

3 years ago

0.4.2

3 years ago

0.3.0

3 years ago

0.2.1

3 years ago

0.1.2

3 years ago

0.2.0

3 years ago

0.1.3

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago