Core settings and commands affect the entire messaging widget.

Show

zE('messenger', 'show');

Displays the widget on the host page in the state it was in before it was hidden. The widget is displayed by default on page load. You don't need to call show to display the widget unless you use hide.

Parameters

None

Hide

zE('messenger', 'hide');

Hides all parts of the widget from the page. You can invoke it before or after page load.

Parameters

None

Open

zE('messenger', 'open');

Opens the messaging Web Widget.

Parameters

None

Close

zE('messenger', 'close');

Closes the messaging Web Widget.

Parameters

None

Custom Launcher

To create a custom messaging Web Widget launcher and define how it behaves, use the open, close & unreadMessages API and launcher settings for Messaging in admin center.

Set locale

zE('messenger:set', 'locale', newLocale<string>)

Sets the locale of the messaging Web Widget. It overrides the messaging Web Widget's default behavior of matching the same language an end user has set in their web browser.

The command takes a locale string as an argument. For a list of supported locales and associated codes, use the following Zendesk public REST API endpoint: https://support.zendesk.com/api/v2/locales/public.json.

Note: This code should be placed immediately after the messaging Web Widget code snippet.

Parameters

  • newLocale: String. The locale string to change the locale to.

Example

zE("messenger:set", "locale", "es")

Set zIndex

zE('messenger:set', 'zIndex', newZIndex<number>);

Sets the CSS property z-index on all the iframes for the messaging Web Widget.

When two elements overlap, the z-index values of the elements determine which one covers the other. An element with a greater z-index value covers an element with a smaller one.

By default, all iframes in the messaging Web Widget have a z-index value of 999999.

Parameters

  • newZIndex: Number. The z-index value to use for all iframes for the messaging Web Widget

Example

zE("messenger:set", "zIndex", 123)

Set cookies

zE('messenger:set', 'cookies', range<enum>);

The messaging Web Widget uses a mixture of cookies as well as local and session storage in order to function.

The messaging Web Widget defines three cookies categories: essential, functional, and analytics. For more information, see Zendesk In-Product Cookie Policy. By default, Web Widget stores essential, functional, and analytics cookies.

If the end user has opted in for all cookies, you can set range as "all" to let the messaging Web Widget know that all cookies, including analytics cookies, should be stored.

If the end user has opted out of cookies, you can set range to "none" to let the messaging Web Widget know that it is unable to use any of these storage options. Setting range to "none" will result in the messaging Web Widget being hidden from the end user and all values in local and session storage being deleted.

If the end user has opted out of analytics cookies, you can set range as "functional" to let the messaging Web Widget know that all cookies, besides analytics cookies, should be stored.

Note: Analytics cookies are currently used in two functionalities: Pages viewed (Visitor's path) and Proactive messages analytics. Disabling analytics cookies will cause the absence of these features.

Parameters

  • range: Enum. The only acceptable values are all, functional, and none.

Example

zE("messenger:set", "cookies", "all")

Set Conversation Fields

zE('messenger:set', 'conversationFields', conversationFields<{ id: <string>, value: <string|number|boolean> }[]>;

Sets values for custom ticket fields on the conversation. Each field is identified by its ticket field id and must already be created in Admin Center as a custom ticket field configured to allow end users to set values. conversationFields maps data to specific, structured ticket fields that agents can see on the support ticket. If you want to store free-form key-value pairs, use conversationMetadata instead. To use conversation fields, see Using Messaging Metadata with the Zendesk Web Widget and SDKs.

Note: Conversation fields aren't immediately associated with a conversation when the API is called. It'll only be applied when end users start a conversation or send a message in an existing conversation from the page it's called from. Associating conversation fields with a conversation is an asynchronous operation. Use callback to make sure your fields will be associated properly. Additionally, conversation fields are added to the support ticket at the time of ticket creation, including AI Agent read-only tickets. This API can't be used to update metadata of an existing ticket.

System ticket fields, such as the Priority field, are not supported.

Conversation fields are cleared when the reset widget API or authentication API to sign-out is called. The conversationFields API needs to be called again to apply field metadata to a fresh conversation.

Parameters

  • conversationFields: Array. Formatted as an array of objects with id and value properties.
PropertyTypeDescription
idstringid of custom ticket field
valuestring, number or booleanvalue of custom ticket field
  • callback: Function. Optional parameter.

Examples

For example, if the id of your custom field for order total is 123456789 and you want to set its value to 100.50, then you would call:

zE("messenger:set", "conversationFields", [{ id: "123456789", value: 100.5 }])

Also, if you want to make sure that your conversation fields were set properly before opening the messaging Web Widget, then you would call:

const openWidget = () => {  // your function to trigger messaging Web Widget to open}
zE(  "messenger:set",  "conversationFields",  [{ id: "123456789", value: 100.5 }],  openWidget)

Set Conversation Tags

zE('messenger:set', 'conversationTags', conversationTags<string[]>);

Allows custom conversation tags to be set in the client to add contextual data about the conversation. To learn more about Messaging Metadata, see Introduction to Messaging Metadata.

Conversation tags do not need any prerequisite steps before the API can be used. To use conversation tags, see Using Messaging Metadata with the Zendesk Web Widget and SDKs.

Note: Conversation tags aren't immediately associated with a conversation when the API is called. It'll only be applied when end users start a conversation or send a message in an existing conversation from the page it's called from. Additionally, conversation tags are added to the support ticket at the time of ticket creation. This API can't be used to update metadata of an existing ticket.

Conversation tags are cleared when the reset widget API or authentication API to sign-out is called. The conversationTags API needs to be called again to apply tag metadata to a fresh conversation.

Parameters

  • conversationTags: Array. Formatted as an array of strings.

Example

For example, to apply sales and computer_accessories tags to a sales conversation about computer accessories, then you would call:

zE("messenger:set", "conversationTags", ["sales", "computer_accessories"])

Set Behavior

zE('messenger:set', 'behavior', behaviorOptions<object>);

Updates runtime behavior settings for the messaging Web Widget.

Use this API to adjust the widget's settings dynamically based on specific user actions or page conditions.

Parameters

  • behaviorOptions: Object. Configuration for widget behavior.

    PropertyTypeRequiredDescription
    composerobjectNoComposer behavior configuration
    composer.focusobjectNoComposer focus behavior configuration
    composer.focus.suppressAutoFocusbooleanNoSuppresses auto-focus on the composer when new messages arrive. When false (default), the chat input automatically gains focus when new messages arrive.
    headerobjectNoHeader behavior configuration
    header.logoobjectNoHeader logo configuration
    header.logo.altTextstringNoCustom alt text for the header logo image, used by screen readers. If not provided, defaults to the Company logo translation. Set to an empty string to suppress the screen reader announcement.

Examples

zE("messenger:set", "behavior", {  composer: {    focus: {      suppressAutoFocus: true    }  }})
zE("messenger:set", "behavior", {  header: {    logo: {      altText: "The Atlantic logo"    }  }})

Set Delegate - Before Message Sent

zE('messenger:set', 'beforeMessageSent', callback<function>);

Registers a callback to intercept and modify message metadata before a message is sent by the end user. This allows for dynamic metadata modification or addition based on the application's state. The callback is invoked synchronously and must return a modified message object or null/undefined to keep the original message.

Note: This API only allows the modification of the metadata field. Attempts to modify read-only fields (type, receivedAt) will be ignored with a warning. Using metadata to store sensitive information is not recommended.

Parameters

  • callback: Function. Required. The callback receives two parameters: message <object> and data <object>.

The message object <object> has the following structure:

{  metadata: object //Message metadata (can be modified)  type: string //Message type (read-only)  receivedAt: string //Timestamp when message was received (read-only)}

The data object <object> has the following structure:

{  conversationId: string //The ID of the conversation}

The callback must return:

  • A modified message object with updated metadata
  • null or undefined to use the original message unchanged

Important: The callback must be synchronous. Returning a Promise will result in the original message being used.

Return Value

Returns an unsubscribe function that removes the callback when called.

Example

const unsubscribe = zE("messenger:set", "beforeMessageSent", function (message, data) {  // Add custom metadata to every message  return {    ...message,    metadata: {      ...message.metadata,      userId: getCurrentUserId(), // Your custom function      sessionId: getSessionId(), // Your custom function      timestamp: new Date().toISOString()    }  }})
// Later, to remove the callback:unsubscribe()

Set Delegate - Before Message Display

zE('messenger:set', 'beforeMessageDisplay', callback<function>);

Registers a callback to intercept and modify incoming messages before they are displayed to the end user. This allows you to customize the display name of message senders. The callback is invoked synchronously and must return a modified message object, null to hide the message, or undefined to keep the original message.

Note: This API only allows modifying the author.displayName field. Attempts to modify read-only fields (id, type, receivedAt) will be ignored with a warning. These modifications affect only the UI and will thus not be included in the conversation transcript.

Parameters

  • callback: Function. Required. The callback receives two parameters: message <object> and data <object>.

The message object <object> has the following structure:

{  id: string //Message ID (read-only)  author: {    displayName: string //Display name of the message sender (can be modified)  }  metadata: object //Message metadata (read-only for display)  type: string //Message type (read-only)  receivedAt: string //Timestamp when message was received (read-only)}

The data object <object> has the following structure:

{  conversationId: string //The ID of the conversation}

The callback must return:

  • A modified message object with updated author.displayName
  • null to hide the message from display
  • undefined to use the original message unchanged

Important: The callback must be synchronous. Returning a Promise will result in the original message being used.

Example

const unsubscribe = zE("messenger:set", "beforeMessageDisplay", function (message, data) {  // Customize agent display names  if (message.author.displayName === 'Support Agent') {    return {      ...message,      author: { displayName: 'Customer Success Team' }    }  }    // Keep original message  return message})
// Later, to remove the callback:unsubscribe()

Update User

zE('messenger', 'updateUser', metadata, callback)

Partially updates the existing user with the provided key-value pairs. The API uses a 500 ms debounce, so multiple rapid calls are combined into a single request before sending. The optional callback runs after the request is dispatched.

Parameters

  • metadata: Object. Key-value pairs to update on the user.
PropertyTypeDescription
[key]string, number, or booleanA user property to update
  • callback: Function. Optional parameter. Executes after the update request is dispatched.

Example

zE("messenger", "updateUser", { name: "Jane Doe", plan: "enterprise", active: true }, function () {  console.log("User updated")})

Set User Metadata

zE('messenger:set', 'userMetadata', metadata, callback)

Stores key-value pairs as user properties when the Sunshine Conversations user is first created. These values apply only at creation time and are not retroactively applied to existing users.

Parameters

  • metadata: Object. Key-value pairs to set on the user at creation.
PropertyTypeDescription
[key]string, number, or booleanA user property to set on creation
  • callback: Function. Optional parameter.

Example

zE("messenger:set", "userMetadata", { plan: "enterprise", region: "us-west" })

Set Conversation Metadata

zE('messenger:set', 'conversationMetadata', metadata, callback)

Attaches arbitrary key-value pairs as metadata on the next conversation or message. Unlike conversationFields, which maps data to pre-defined custom ticket fields visible to agents, conversationMetadata stores free-form context that doesn't require any Admin Center setup and is not surfaced as structured ticket fields. Conversation metadata is cleared when the reset widget API or authentication API to sign-out is called.

Note: Conversation metadata is not immediately associated with a conversation when the API is called. It will only be applied when the end user starts a conversation or sends a message in an existing conversation from the page it's called from.

Parameters

  • metadata: Object. Key-value pairs to attach to the next conversation or message.
PropertyTypeDescription
[key]string, number, or booleanA metadata property to attach
  • callback: Function. Optional parameter.

Example

zE("messenger:set", "conversationMetadata", { orderId: "9876", category: "returns", urgent: true })

Reset Widget

zE('messenger', 'resetWidget', callback<function>)

The resetWidget method clears all widget local state, including user data, conversations, and connections. It also clears all conversation tags and conversation fields data. Use the Conversation Fields and Tags API again to apply conversation fields and tags data to a new conversation. The resetWidget method accepts an optional callback function that executes after the reset completes successfully. The method also performs validation checks to ensure the widget isn't in a pending state before proceeding with the reset operation. This helps to prevent problems such as race conditions and abnormal application states.

Parameters

  • callback: Function. Executes when the widget has been reset successfully

Example

zE("messenger", "resetWidget", function () {  console.log(`You have reset the messaging Web Widget`)})

Set Customization

zE('messenger:set', 'customization', customizationOptions<object>);

Dynamically updates the Web Widget Messenger's appearance and behavior. The Customization API lets you adjust the widget using configuration objects for theme colors, common settings, conversation list, and message log.

Parameters

  • theme: Object. Optional parameter. Defines the color palette for supported UI elements of the Web Widget Messenger. The theme object accepts any subset of supported color properties, allowing you to customize one or many aspects of the messenger's appearance. Each property must be a valid CSS color string (for example, hex, rgb, hsl, or named color). If a property is not provided, the widget uses the default color. See Customizing Web Widget colors.

  • common: Object. Optional parameter. Settings that apply globally to all parts of the widget.

    PropertyTypeDescription
    hideHeaderbooleanHides the header across both the conversation list and the message log
    contentScalenumberAdjusts the widget's content scaling as a percentage (range: 50-200, default: 100)
  • conversationList: Object. Optional parameter. Settings that customize the conversation list.

    PropertyTypeDescription
    hideNewConversationButtonbooleanHides the "New Conversation" button
    hideHeaderbooleanHides the header only on the conversation list
  • messageLog: Object. Optional parameter. Settings that customize the message log view.

    PropertyTypeDescription
    hideHeaderbooleanIf true, hides the header on the message log page
    avatarobjectCustomizes the avatar appearance in the message log
    avatar.hiddenbooleanIf true, the avatar is completely hidden. Default: false
    avatar.positionstringAvatar placement relative to message bubbles. Accepted values: "side", "top", "top-side". Default: "side"
    avatar.sizenumberAvatar size in pixels (range: 16–64). Default: 32
    businessMessageobjectCustomizes the appearance of agent/business message bubbles
    businessMessage.bubbleMaxWidthnumberMaximum width of the bubble as a percentage (range: 10–100). Default: uses responsive breakpoints
    businessMessage.hideBubblebooleanIf true, hides the bubble background behind the message text. Default: false
    userMessageobjectCustomizes the appearance of end-user message bubbles
    userMessage.bubbleMaxWidthnumberMaximum width of the bubble as a percentage (range: 10–100). Default: uses responsive breakpoints
    userMessage.hideBubblebooleanIf true, hides the bubble background behind the message text. Default: false
  • position: Object. Optional parameter. Controls where the widget appears on the screen. Only applies in floating mode.

    Position settings configured in admin center are applied when the widget initializes. Calling position through this API at any point in the widget lifecycle - including before or after the widget has fully loaded - will override those admin center settings for the current page session.

    PropertyTypeDescription
    sidestringThe side of the screen where the widget is displayed. Accepted values: 'left', 'right'. Default: 'right'
    offsetobjectDistance of the widget from the screen edges, in pixels
    offset.webobjectOffset configuration for web. Must contain at least one of horizontal or vertical
    offset.web.horizontalnumberHorizontal distance from the screen edge, in pixels. Default: 16
    offset.web.verticalnumberVertical distance from the bottom of the screen, in pixels. Default: 16
    offset.mobileobjectOffset configuration for mobile. Must contain at least one of horizontal or vertical
    offset.mobile.horizontalnumberHorizontal distance from the screen edge, in pixels. Default: 16
    offset.mobile.verticalnumberVertical distance from the bottom of the screen, in pixels. Default: 16

Examples

Theme customization:

zE("messenger:set", "customization", {  theme: {    primary: "#FE5E41",    onPrimary: "#FFFFFF",    message: "#F3C178",    onMessage: "#5F0F00",    action: "#B0DB43",    onAction: "#000000",    businessMessage: "#fff",    onBusinessMessage: "#F10404",    background: "#DFE0E2",    onBackground: "#F10404",    error: "#FF1744",    onError: "#FFFFFF",    notify: "#FF007F",    onNotify: "#FFFFFF",    onSecondaryAction: "#000000"  }})

Hide header globally:

zE("messenger:set", "customization", {  common: {    hideHeader: true  }})

Adjust content scale:

zE("messenger:set", "customization", {  common: {    contentScale: 125  }})

Hide new conversation button:

zE("messenger:set", "customization", {  conversationList: {    hideNewConversationButton: true  }})

Position the widget on the left side:

zE("messenger:set", "customization", {  position: {    side: "left"  }})

Dynamic positioning for RTL languages:

Because the position API can be called at any point in the widget lifecycle, it is well suited for dynamic layout changes. For example, if your page supports switching between left-to-right (LTR) and right-to-left (RTL) languages, you can move the widget to the appropriate side whenever the language changes:

function onLanguageChange(locale) {  const isRTL = getRTLLocales().includes(locale)  zE("messenger:set", "locale", locale)  zE("messenger:set", "customization", {    position: { side: isRTL ? "left" : "right" }  })}

Set a custom offset from the screen edges:

zE("messenger:set", "customization", {  position: {    offset: {      web: { horizontal: 32, vertical: 24 },      mobile: { horizontal: 16, vertical: 16 }    }  }})

Combine side and offset:

zE("messenger:set", "customization", {  position: {    side: "left",    offset: {      web: { horizontal: 20, vertical: 20 }    }  }})

Full customization example:

zE("messenger:set", "customization", {  theme: {    primary: "#FE5E41",    onPrimary: "#FFFFFF",    message: "#F3C178",  },  common: {    contentScale: 110,    hideHeader: false  },  conversationList: {    hideNewConversationButton: true,    hideHeader: false  },  messageLog: {    hideHeader: true  },  position: {    side: "right",    offset: {      web: { horizontal: 16, vertical: 16 }    }  }})

Customize message bubbles:

zE("messenger:set", "customization", {  messageLog: {    businessMessage: {      bubbleMaxWidth: 80,      hideBubble: false    },    userMessage: {      bubbleMaxWidth: 60,      hideBubble: true    }  }})

Customize avatar:

zE("messenger:set", "customization", {  messageLog: {    avatar: {      hidden: false,      position: "top",      size: 32    }  }})

Create New Conversation (UI)

zE('messenger:ui', 'newConversation', conversationOptions<object>, errorCallback<function>);

Creates a new conversation and immediately navigates to the message log. This is an asynchronous operation intended for UI-triggered actions. The widget automatically opens to the new conversation view after creation.

Use this API when you want to trigger a new conversation from your UI (for example, from a custom button).

Note: This API does not support message metadata. For programmatic control with full callback support (including response data) and message metadata support, use zE('messenger', 'newConversation') instead.

Parameters

NameTypeMandatoryDescription
conversationOptionsobjectfalseConfiguration for the new conversation
errorCallbackfunctionfalseA callback function to handle the result of the conversation creation

Conversation Options Object Properties

Conversation Options:

PropertyTypeRequiredDescription
displayNamestringNoConversation title
iconUrlstringNoIcon URL of the conversation
metadataobjectNoFlat key/value pairs of conversation metadata (string, number, or boolean values)
messageobjectNoInitial message to pre-populate in the message log when the conversation is created

When message is omitted, the conversation is created without an initial message and behavior is unchanged.

When message is provided, the message text appears immediately in the message log once the conversation is created.

The message object has the following structure:

PropertyTypeRequiredDescription
message.contentobjectYesThe content of the initial message
message.content.typestringYesMust be 'text'. Only text messages are supported.
message.content.textstringYesThe message text. Must be a non-empty, non-whitespace string.

Important: message.metadata is not supported by this API. Any metadata passed in the message object will be ignored. To attach metadata to the initial message, use zE('messenger', 'newConversation') instead.

If message is provided but invalid (wrong type, empty or whitespace-only text, missing content, etc.), an error is logged and the conversation is not created.

Error Callback

When errorCallback is called, it receives an error parameter which will be either:

  • null, indicating a successful conversation creation
  • An instance of ConversationCreationError which contains information about why the conversation creation failed

The ConversationCreationError class has the following properties:

NameTypeDescription
messagestringA descriptive message that explains the error
reasonstringProvides additional details on the cause of the conversation creation failure
typestringIdentifies the error type as ConversationCreationError

Possible Error Reasons

ReasonDescription
Invalid configurationOne or more options in conversationOptions failed validation
Conversation creation failedUser creation, connection initialization, or conversation creation failed after validation.

Examples

Create conversation with default settings:

zE("messenger:ui", "newConversation")

Create conversation with display name:

zE("messenger:ui", "newConversation", {  displayName: "Technical Support"})

Create conversation with error callback:

zE("messenger:ui", "newConversation",  { displayName: "Support Chat" },  function (error) {    if (error) {      console.error("Failed to create conversation:", error.reason, error.message)    } else {      console.log("Conversation created successfully")    }  })

Create conversation with an initial message:

zE("messenger:ui", "newConversation", {  displayName: "Support Chat",  message: {    content: {      type: "text",      text: "I need help with my order #12345"    }  }},  function errorCallback(error) {    if (error) {      // Example error handling      const { type, reason, message } = error      console.error(`Conversation creation failed: ${reason} - ${message}`)    } else {        console.log("Conversation created successfully")    }  }})

Create conversation with full options and error handling:

zE("messenger:ui", "newConversation", {  displayName: "Support Request",  iconUrl: "https://example.com/icon.png",  metadata: {    priority: "high",    orderId: 12345  },  message: {    content: {      type: "text",      text: "I need help with my order #12345"    }    // Note: message.metadata is NOT supported in this API  }})

Create New Conversation (Programmatic)

zE('messenger', 'newConversation', conversationOptions<object>, callback<function(error, response)>);

Creates a new conversation with callback support for handling success and error cases. Use this API when you need programmatic access to the conversation details, error handling, or want to attach metadata to the initial message.

Unlike the UI version, this API does not automatically navigate to the conversation and requires a callback function to handle the result.

Parameters

  • conversationOptions: Object. Optional parameter. Configuration for the new conversation.

    PropertyTypeRequiredDescription
    descriptionstringNoConversation description
    displayNamestringNoConversation title
    iconUrlstringNoIcon URL of the conversation. Must be a valid URL
    metadataobjectNoFlat key/value pairs of conversation metadata (string, number, or boolean values only)
    messageobjectNoInitial message to pre-populate in the message log when the conversation is created

    When message is omitted, the conversation is created without an initial message.

    When message is provided, the message is sent immediately when the conversation is created.

    The message object has the following structure:

    PropertyTypeRequiredDescription
    message.contentobjectYesThe content of the initial message
    message.content.typestringYesMust be 'text'. Only text messages are supported
    message.content.textstringYesThe message text. Must be a non-empty, non-whitespace string
    message.metadataobjectNoFlat key/value pairs of message-level metadata (string, number, or boolean)

    If message is provided but invalid (for example, wrong type, empty or whitespace-only text or missing content), an error is passed to the callback and the conversation is not created.

  • callback: Function. Required. The callback receives an error <ConversationCreationError | null> as the first parameter and a response as the second parameter when successful.

When an error occurs (error is not null), the error object <object> has the following structure:

{  type: "ConversationCreationError" //Error type identifier  reason: string //Either 'Invalid configuration' or 'Conversation creation failed'  message: string //A descriptive error message}

When successful (error is null), the response object <object> has the following structure:

{  id: string //The unique identifier of the conversation  createdAt: number //Unix timestamp when the conversation was created  lastUpdatedAt: number //Unix timestamp of the last update  displayName: string | null //The conversation's display name  iconUrl: string | null //The conversation's icon URL  status: "active" | "idle" //The conversation status  type: string //The conversation type (e.g., 'personal')  brandId: string | null //The brand identifier  unreadCount: number //The number of unread messages}

Examples

Create conversation with callback:

zE(  "messenger",  "newConversation",  {    displayName: "Technical Support"  },  (error, conversation) => {    if (error) {      console.error("Failed:", error)      return    }    console.log("Created:", conversation)  })

Create conversation with an initial message:

zE(  "messenger",  "newConversation",  {    displayName: "Friday order",    message: {      content: {        type: "text",        text: "Hello, I need help with my order."      }    }  },  (error, conversation) => {    if (error) {      console.error("Failed:", error.message)      return    }    console.log("Created:", conversation.id)  })

Create an empty conversation:

zE("messenger", "newConversation", undefined, (error, conversation) => {  if (error) {    console.error("Error:", error.message)    return  }  console.log("Created:", conversation.id)})

Create conversation with message metadata:

zE(  "messenger",  "newConversation",  {    displayName: "VIP Support",    description: "Order #13377430",    iconUrl: "https://example.com/icon.png",    metadata: {      orderId: "13377430",      priority: "high",      vip: true    },    message: {      content: {        type: "text",        text: "I have a question about my order."      },      metadata: {        intent: "order_inquiry",        source: "checkout"      }    }  },  (error, conversation) => {    if (error) {      console.error("Error type:", error.type)      console.error("Reason:", error.reason)      console.error("Message:", error.message)      return    }    console.log("Conversation ID:", conversation.id)    console.log("Brand ID:", conversation.brandId)    console.log("Full response:", conversation)  })

Send Message

zE('messenger', 'sendMessage', message<object>, conversationId<string>, callback<function(error, response)>);

Sends a message on behalf of the end user to an existing conversation.

Parameters

  • message: Object. Required. The message to send.

    PropertyTypeRequiredDescription
    contentobjectYesThe content of the message
    content.typestringYesMust be 'text'. Only text messages are supported
    content.textstringYesThe message text. Must be a non-empty, non-whitespace string
    metadataobjectNoFlat key/value pairs of message-level metadata (string, number, or boolean)
  • conversationId: String. Required. The unique identifier of the conversation to send the message to.

  • callback: Function. Required. The callback receives an error <SendMessageError | null> as the first parameter and a response as the second parameter when successful.

When an error occurs (error is not null), the error object <object> has the following structure:

{  type: "SendMessageError" //Error type identifier  reason: string //One of: 'Invalid message', 'Invalid conversationId', 'No user', 'Conversation not found', 'Message send failed'  message: string //A descriptive error message}

When successful (error is null), the response object <object> has the following structure:

{  id: string | null //The unique identifier of the message  receivedAt: number //Unix timestamp when the message was received}

Examples

Send a simple text message:

zE(  "messenger",  "sendMessage",  {    content: {      type: "text",      text: "Hello, I need help with my order."    }  },  "12345",  (error, message) => {    if (error) {      console.error("sendMessage failed", error)      return    }    console.log("sent message id", message.id)  })

Send a message with metadata:

zE(  "messenger",  "sendMessage",  {    content: { type: "text", text: "Hello, I need help with my order." },    metadata: {      intent: "order_inquiry",      orderId: "67890",      source: "checkout"    }  },  "12345",  (error, message) => {    if (error) {      console.error("Error type:", error.type)      console.error("Reason:", error.reason)      console.error("Message:", error.message)      return    }    console.log("Message ID:", message.id)    console.log("Sent at:", new Date(message.received))    console.log("Full response:", message)  })

Fetch Conversations

zE('messenger', 'fetchConversations', offset<number>, callback<function(error, response)>);

Retrieves a paginated list of conversations for the current user, with up to 10 conversations per request.

Parameters

  • offset: Number. Required. The starting index for pagination. Must be a non-negative integer. Use 0 to fetch the first page.

  • callback: Function. Required. The callback receives an error <FetchConversationsError | null> as the first parameter and a response as the second parameter when successful.

When successful (error is null), the response object contains:

{  data: [ // Array of conversation objects (up to 10 per page)    {      id: string, // The conversation ID      createdAt: number, // Creation timestamp (milliseconds or seconds)      lastUpdatedAt: number, // Last update timestamp      displayName: string | null, // Display name of the conversation, or null if none      iconUrl: string | null, // Icon URL for the conversation, or null if none      status: 'active' | 'idle', // Conversation status      type: string, // Conversation type identifier      brandId: string | null, // Associated brand ID, or null if none      unreadCount: number // Number of unread messages    }  ],  hasMore: boolean // Whether there are more conversations available to fetch}

When an error occurs (error is not null), the error object contains:

{  type: 'FetchConversationsError' //Error type identifier  reason: string //Either 'Invalid offset', 'No user' or 'Failed to fetch conversations'  message: string //A descriptive error message}

Example

// Fetch first page of conversationszE("messenger", "fetchConversations", 0, (error, response) => {  if (error) {    console.error("Failed to fetch conversations:", error.reason)    return  }
  console.log("Fetched conversations:", response.data)  console.log("Has more pages:", response.hasMore)
  // Fetch next page if available  if (response.hasMore) {    zE("messenger", "fetchConversations", 10, (error, nextResponse) => {      // Handle next page...    })  }})

Get Config

zE('messenger:get', 'config', callback<function>)

Retrieves the current configuration state of the messaging Web Widget. If the widget configuration hasn't loaded yet, the callback is deferred until the configuration is received.

Parameters

  • callback: Function. Required. The callback receives a config <object> when executed.

The config object <object> has the following structure:

{  canUserCreateMoreConversations: boolean //Whether the current user is permitted to create additional conversations  multiConvoEnabled: boolean //Whether multi-conversation mode is enabled for the widget  launcherShape: string //The shape of the widget launcher button: 'square', 'circle', or 'none'}

Example

zE("messenger:get", "config", function (config) {  console.log("Widget config:", config)
  if (config.multiConvoEnabled) {    console.log("Multi-conversation mode is enabled")  }
  if (config.launcherShape === "none") {    console.log("No launcher button — using a custom launcher")  }})

zE('messenger:ui', 'navigation', config<object>);

Navigates to a specific screen within the messaging Web Widget. This API is only available in multi-conversation mode and cannot be used in single conversation mode or embedded split view mode.

Parameters

  • config: Object. Required. Configuration specifying which screen to navigate to.

    PropertyTypeRequiredDescription
    screenstringYesOne of: 'ConversationList', 'MostRecentActiveConversation', 'Conversation'
    optionsobjectNoOnly required for 'Conversation' screen. Contains conversationId

    When navigating to a specific conversation, the options object has the following structure:

{  screen: string //One of: 'ConversationList', 'MostRecentActiveConversation', 'Conversation'  options: { //Optional, only required for 'Conversation' screen    conversationId: string //The ID of the conversation to navigate to  }}

Supported Screens:

  • 'ConversationList' - Navigates to the list of conversations
  • 'MostRecentActiveConversation' - Navigates to the most recent active conversation (creates one if none exists)
  • 'Conversation' - Navigates to a specific conversation by ID (requires options.conversationId)

Examples

Navigate to conversation list:

zE("messenger:ui", "navigation", {  screen: "ConversationList"})

Navigate to most recent conversation:

zE("messenger:ui", "navigation", {  screen: "MostRecentActiveConversation"})

Navigate to specific conversation:

zE("messenger:ui", "navigation", {  screen: "Conversation",  options: {    conversationId: "conv_12345"  }})

Notes

  • This API only works when the widget is in multi-conversation mode with the conversation list enabled.
  • An error will be logged if the widget is in single conversation mode or embedded split view mode.
  • If navigating to a conversation that doesn't exist, the widget will fall back to showing the conversation list.

Embedded Mode

zE('messenger', 'render', config<object>, errorCallback<function>);

Renders the widget in either floating or embedded mode. In embedded mode, the widget integrates directly into specified containers on your page, automatically adjusting its dimensions to fit the container.

Disabling Auto-Rendering

To prevent the widget from automatically rendering in floating mode, include the following script before the widget loads:

<script>  window.zEMessenger = {    autorender: false  }</script>

Parameters

NameTypeMandatoryDescription
configobjectfalseConfiguration options for how the widget is rendered. If omitted, the widget renders in floating mode
errorCallbackfunctionfalseA callback function to handle the result of the render attempt

Config Object Properties

PropertyTypeDescription
modestringRender mode: 'embedded' or 'floating'
widgetobjectFull widget configuration
conversationListobjectConversation list configuration
messageLogobjectMessage log configuration

Each component object (widget, conversationList, messageLog) accepts a targetElement property — a CSS selector or element ID that specifies where the component should be rendered.

Note: In embedded mode, your configuration must include at least one of the following: widget, conversationList, or messageLog.

Error Callback

When errorCallback is called, it receives an error parameter which will be either:

  • null, indicating a successful render
  • An instance of RenderFailedError which contains information about why the render failed

The RenderFailedError class has the following properties:

NameTypeDescription
messagestringA descriptive message that explains the error
reasonstringProvides additional details on the cause of the failure
typestringIdentifies the error type as RenderFailedError

Possible Error Reasons

ReasonDescription
InvalidArgumentConfig is not an object
InvalidModeMode is not 'floating' or 'embedded'
MissingEmbeddedConfigurationEmbedded mode without required config
InvalidConfigurationWidget, conversationList, or messageLog is not an object
InvalidTargetElementtargetElement is missing or not a string
TargetElementNotFoundTarget element doesn't exist in the DOM
InvalidCssSelectorCSS selector is invalid

Examples

Full widget in a container:

First, create an HTML container element where you want the widget to appear. This <div> acts as a placeholder on your page:

<div id="my-messenger-container"></div>

Next, use JavaScript to embed the widget inside that container by calling the render method and specifying the target by its selector:

zE("messenger", "render", {  mode: "embedded",  widget: {    targetElement: "#my-messenger-container"  }})

With error handling:

zE("messenger", "render",   {    mode: "embedded",    widget: {      targetElement: "#my-messenger-container"    }  },  function errorCallback(error) {    if (error) {      // Example error handling      const { type, reason, message } = error      console.error(`Render failed: ${reason} - ${message}`)            // Handle specific error types      if (reason === 'TargetElementNotFound') {        console.error("The container element was not found in the DOM")      }    } else {      console.log("Widget rendered successfully")    }  })

Conversation list only:

zE("messenger", "render", {  mode: "embedded",  conversationList: {    targetElement: "#conversations-container"  }})

Message log only:

zE("messenger", "render", {  mode: "embedded",  messageLog: {    targetElement: "#messages-container"  }})

Split view (conversation list + message log):

zE("messenger", "render", {  mode: "embedded",  conversationList: {    targetElement: "#left-sidebar"  },  messageLog: {    targetElement: "#main-content"  }})

Container Availability

Make sure the HTML container element is present in the DOM before calling zE('messenger', 'render', config). If the element is missing, an error will be logged in the console.