@iterable/web-sdk
v1.1.3
Published
Iterable SDK for JavaScript and Node.
Downloads
74,332
Readme
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
- Installation
- Functions
- Classes, interfaces, types, and enums
- FAQ
- Link handling
- TypeScript
- Contributing
- License
Other documentation
This document contains reference information about the Web SDK. For other information, please see:
- In-Browser Messaging Overview
- Embedded Messaging Overview
- Overview of Iterable's Web SDK
- Setting up Iterable's Web SDK
- Embedded Messages with Iterable's Web SDK
Using the SDK
In general, to use the SDK, you'll need to follow these steps:
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.
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.
Install the SDK in your web app.
Use the API key to initialize the SDK, as described in
initialize
andinitializeWithConfig
. 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.To identify the user to the SDK, call
setEmail
orsetUserID
(returned byinitialize
orinitializeWithConfig
). The SDK uses the user'semail
oruserId
to fetch a valid JWT token from your server.After the SDK successfully sets the user's
email
oruserId
and the SDK fetches a JWT token, you can make API requests to Iterable. For example, you can calltrack
to track events, orgetInAppMessages
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 Name | Description |
| --------------------------------------------------------------------------------- | ----------- |
| 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. |
| 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. |
| getInAppMessages
| Fetches in-app messages by calling GET /api/inApp/getMessages
. |
| 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
). |
| 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
). |
| IterableEmbeddedCard
| Returns a string of the HTML for an out-of-the-box card view for an embedded message. |
| IterableEmbeddedBanner
| Returns a string of the HTML for an out-of-the-box banner view for an embedded message. |
| IterableEmbeddedNotification
| Returns a string of the HTML for an out-of-the-box notification view for an embedded message. |
| sortInAppMessages
| Sorts an array of in-app messages by priority, and then creation date. |
| track
| Tracks a custom event by calling POST /api/events/track
. |
| trackEmbeddedClick
| Tracks an embeddedClick
event by calling POST /api/embedded-messaging/events/click
. |
| trackEmbeddedReceived
| Tracks an embeddedReceived
event by calling POST /api/embedded-messaging/events/received
. |
| trackEmbeddedSession
| Tracks an embeddedSession
event and related embeddedImpression
events by calling POST /api/embedded-messaging/events/session
. | |
| trackInAppClick
| Tracks an inAppClick
event by calling POST /api/events/trackInAppClick
. |
| trackInAppClose
| Tracks an inAppClose
event by calling POST /api/events/trackInAppClose
. |
| trackInAppConsume
| Deletes an in-app message from the server by calling POST /api/events/trackInAppConsume
. |
| trackInAppDelivery
| Tracks an inAppDelivery
event by calling POST /api/events/trackInAppDelivery
. |
| trackInAppOpen
| Tracks an inAppOpen
event by calling POST /api/events/trackInAppOpen
. |
| trackPurchase
| Tracks a purchase
event by calling POST /api/commerce/trackPurchase
. |
| updateCart
| Updates the shopping cart items on the user's Iterable profile by calling POST /api/commerce/updateCart
. |
| updateSubscriptions
| Updates the user's subscriptions by calling POST /api/users/updateSubscriptions
. |
| updateUser
| Updates the data on a user's Iterable profile by calling POST /api/users/updateUser
. |
| 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. |
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 Name | Description | Value | Default |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | ----------- |
| animationDuration
| How long (in ms) it should take messages to animate in and out | number
| 400
|
| bottomOffset
| How much space (px or %) to create between the bottom of the screen and a message. Not applicable for center, top, or full-screen messages. | string
| undefined
|
| closeButton
| Properties that define a custom close button to display on a message. | CloseButtonOptions
(see below) | undefined
|
| displayInterval
| How long (in ms) to wait before showing the next in-app message after closing the currently open one | number
| 30000
|
| handleLinks
| How 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
|
| onOpenNodeToTakeFocus
| The 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. | string
| undefined
|
| onOpenScreenReaderMessage
| The text a screen reader should read when opening the message. | string
| undefined
|
| rightOffset
| The amount of space (px or %) to create between the right of the screen and the message. Not applicable for center or full-screen messages. | string
| undefined
|
| topOffset
| How much space (px or %) to create between the top of the screen and a message. Not applicable for center, bottom, or full-screen messages. | string
| undefined
|
closeButton
options (see CloseButton
):
| Property Name | Description | Value | Default |
| --------------------------- | ---------------------------------------------------------------------------- | -------------------------- | ------------- |
| color
| The button's color (does not affect custom icons) | string
| undefined
|
| iconPath
| Custom pathname to an image or SVG to use (instead of the default "X") | string
| undefined
|
| isRequiredToDismissMessage
| If true
, users cannot dismiss in-app messages by clicking outside of them. | boolean
| undefined
|
| position
| Where the button should display on an in-app message | 'top-right' \| 'top-left'
| 'top-right'
|
| sideOffset
| How much space to leave between the button and side of the container | string
| '4%'
|
| size
| How large to set the width, height, and font-size | string \| number
| 24
|
| topOffset
| How much space to leave between the button and the top of the container | string
| '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 yourgetInAppMessages
requests to useoptions: { 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
– TheIterableEmbeddedMessage
object that represents the message you want to display.htmlElements
– Custom styles (typeElements
) 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 trackingembeddedClick
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:
- Out-of-the-Box Views.
- For default card styles, see the
src/components/card/styles.ts
in the Web SDK GitHub repository. - To learn how to apply custom styles, see Custom Styles.
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
– TheIterableEmbeddedMessage
object that represents the message you want to display.htmlElements
– Custom styles (typeElements
) 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 trackingembeddedClick
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:
- Creating an Out-of-the-Box View.
- For default banner styles, see the
src/components/banner/styles.ts
in the Web SDK GitHub repository. - To learn how to apply custom styles, see Custom Styles.
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
– TheIterableEmbeddedMessage
object that represents the message you want to display.htmlElements
– Custom styles (typeElements
) 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 trackingembeddedClick
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:
- Creating an Out-of-the-Box View.
- For default notification styles, see the
src/components/notification/styles.ts
- To learn how to apply custom styles, see Custom Styles.
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('[email protected]').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.
| Type | Description |
| --------------------------------------------------------------------------------- | ----------- |
| CloseButton
| Specifies how the SDK should display a close button on the associated in-app message. Passed as part of InAppMessagesRequestParams
. |
| CloseButtonPosition
| Specifies the position of the close button on the associated in-app message. |
| CommerceItem
| An item being purchased or added to a shopping cart. Include when calling trackPurchase
or updateCart
. |
| CommerceUser
| Information about the user associated with a purchase or cart update. Include when calling trackPurchase
or updateCart
. |
| DisplayOptions
| Display options to pass to getInAppMessages
to indicate whether messages should be displayed immediately or later. |
| DisplayPosition
| Describes where an in-app message should be displayed. Part of WebInAppDisplaySettings
. |
| Elements
| Custom styles to apply to IterableEmbeddedCard
, IterableEmbeddedBanner
, and IterableEmbeddedNotification
views for embedded messages. |
| GenerateJWTPayload
| The payload to pass to the generateJWT
function when calling initialize
or initializeWithConfig
. |
| 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. |
| GetInAppMessagesResponse
| Return value for getInAppMessages
, when it's called without the options
parameter. |
| HandleLinks
| Describes where in-app links should be opened. Part of InAppMessagesRequestParams
. |
| InAppMessage
| A single in-app message. |
| InAppDisplaySetting
| Display settings for an in-app message, including padding percentages. |
| InAppEventRequestParams
| Data to pass to trackInAppClick
, trackInAppClose
, trackInAppConsume
, trackInAppDelivery
, and trackInAppOpen
. |
| InAppMessagesRequestParams
| Data to pass to getInAppMessages
. |
| InAppMessageResponse
| Return value for getInAppMessages
, when it's called with the options
parameter. |
| InAppTrackRequestParams
| Data to pass to track
. |
| IterableAction
| An action associated with a click. The type of the action, and its associated URL. |
| IterableActionContext
| Information about the context of an IterableAction
. For example, the associated message type. Only used with embedded messages. |
| IterableActionSource
| An enum of possible message types to which an IterableAction
can be associated. Currently, only EMBEDDED
is supported. |
| 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. |
| 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. |
| IterableEmbeddedButton
| Payload for a button associated with an embedded message. |
| IterableEmbeddedButtonAction
| Payload for the action associated with an embedded message button. |
| IterableEmbeddedClickRequestPayload
| Data to pass to trackEmbeddedClick
. |
| IterableEmbeddedDefaultAction
| The default action associated with an embedded message. Invoked when a user clicks on an embedded message, but outside of its buttons. |
| IterableEmbeddedElements
| Content associated with an embedded message — title, body, media URL, buttons, default action, and extra text fields. |
| 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. |
| IterableEmbeddedManager
| Used to fetch embedded messages from Iterable, and pass them to application code as necessary. |
| IterableEmbeddedMessage
| A single embedded message to display, including title text, body text, buttons, an image URL, click actions, text fields, and JSON data. |
| IterableEmbeddedMessageUpdateHandler
| An 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. |
| IterableEmbeddedMetadata
| Identifying information about an embedded message. |
| IterableEmbeddedSession
| Represents 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. |
| IterableEmbeddedSessionManager
| Used to track sessions and impressions, and to save them back to Iterable. |
| IterableEmbeddedSessionRequestPayload
| Data 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. |
| IterableEmbeddedText
| Extra 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. |
| IterableErrorStatus
| Errors that can come back with an IterableResponse
. |
| IterablePromise
| A promise. |
| IterableResponse
| A response from Iterable's API. |
| IterableUrlHandler
| An 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. |
| OOTB
| A type that defines the parameters to provide when calling IterableEmbeddedCard
, IterableEmbeddedBanner
, and IterableEmbeddedNotification
. |
| Options
| Configuration options to pass to initializeWithConfig
. |
| OutOfTheBoxButton
| Custom styles to apply to buttons in an embedded message. The same as OutOfTheBoxElement
, but with an extra disabledStyles
string. |
| OutOfTheBoxElement
| The custom styles to apply to a single element of an embedded message. |
| SDKInAppMessagesParams
| Parent interface for InAppMessagesRequestParams
. |
| TrackPurchaseRequestParams
| Parameters to pass to trackPurchase
. |
| UpdateCartRequestParams
| Data to pass to updateCart
. |
| UpdateSubscriptionParams
| Data to pass to updateSubscriptions
. |
| UpdateUserParams
| Data to pass to updateUser
. |
| WebInAppDisplaySettings
| An object that contains information about how to display the associated in-app message. |
| WithJWT
| Return value from initialize
and initializeWithConfig
. |
| WithJWTParams
| Parameters 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
isopenUrl
anddata
contains the URL. - For Custom action actions,
type
is the URL, anddata
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
isopenUrl
anddata
contains the URL. - For Custom action actions,
type
is the URL, anddata
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
isopenUrl
anddata
contains the URL. - For Custom action actions,
type
is the URL, anddata
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. IfplacementIds
is provided, fetches only messages for those placements. Callscallback
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 theIterableEmbeddedMessageUpdateHandler
interface. The SDK calls the object'sonMessagesUpdated
andonEmbeddedMessagingDisabled
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 onIterableConfig
.action://
URLs are passed to the custom action handler, and other URLs are passed to the URL handler. The SDK does not currently supportiterable://
URLs for embedded messages.
See also: