Visitar URL original
Core messaging Web Widget API | Zendesk Developer Docs

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.
    messageLogobjectNoMessage log behavior configuration
    messageLog.preConversationobjectNoPre-conversation page configuration
    messageLog.preConversation.enabledbooleanYesIf true, shows the pre-conversation page in the message log before a conversation is created. Default is false
    messageLog.preConversation.settingsobjectNoPre-conversation page content
    messageLog.preConversation.settings.titlestringNoTitle of the pre-conversation page. If not provided, defaults to the Start a conversation translation
    messageLog.preConversation.settings.subtitlestringNoSubtitle of the pre-conversation page. If not provided, defaults to the Start writing to see the conversation here translation
    messageLog.preConversation.settings.iconstringNoIcon URL of the pre-conversation page. Must be a valid http(s) URL
    messageLog.preConversation.settings.promptsstring[]NoSuggested prompts. Selecting a prompt sends it as the first message. Prompts containing square brackets (for example, [order number]) are added to the composer instead

Examples

zE("messenger:set", "behavior", {  composer: {    focus: {      suppressAutoFocus: true    }  }})
zE("messenger:set", "behavior", {  header: {    logo: {      altText: "The Atlantic logo"    }  }})
zE("messenger:set", "behavior", {  messageLog: {    preConversation: {      enabled: true,      settings: {        title: "Technical Support",        subtitle: "Ask us about your order",        icon: "https://example.com/icon.png",        prompts: ["Where is my order?", "I need help with my order [order number]"]      }    }  }})

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, message log, and pre-conversation page.

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
hideHeaderbooleanIf true, hides the header across both the conversation list and the message log. Default is false
contentScalenumberAdjusts the widget's content scaling as a percentage (range: 50-200, default: 100)
stylingPresetstringSelects the overall visual style of the widget. Accepted values: default, minimalistic.

The minimalistic preset applies a compact, chat-style baseline (any option you set explicitly overrides it):
Conversation list — avatar, timestamp, message preview, and divider hidden; grouped by timeframe; selected state on the open conversation.
Message log — business/AI messages render bubbleless (transparent background and border, no padding or radius) while end-user messages keep their bubble; avatar aligned to the top-side; avatar size 24×24px.

  • conversationList

Object. Optional parameter. Settings that customize the conversation list.

PropertyTypeDescription
hideNewConversationButtonbooleanIf true, hides the "New Conversation" button. Default is false
hideHeaderbooleanIf true, hides the header only on the conversation list. Default is false
avatarobjectCustomizes the avatar appearance in the conversation list
avatar.hiddenbooleanIf true, the avatar is completely hidden inside of the conversation list. Default is false
avatar.sizenumberAvatar size in pixels (range: 16–64). Default is 32
avatar.shapestringAvatar shape. Accepted values: square, circle. Default is square
hideTimestampbooleanIf true, hides the timestamp shown on each conversation row. Default is false
hideMessagePreviewbooleanIf true, hides the last-message preview text on each conversation row. Default is false
hideDividerbooleanIf true, hides the divider line between conversation rows. Default is false
groupByTimestampbooleanIf true, groups conversations under time-based headings (Today / Yesterday / Last 7 days / Last 30 days / for earlier months in the current calendar year / for conversations from a previous calendar year). Default is false

  • 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 inside of the message log (excluding header element). Default is false
avatar.positionstringAvatar placement relative to message bubbles. Accepted values: side, top, top-side. Default is side
avatar.sizenumberAvatar size in pixels (range: 16–64). Default is 32
avatar.shapestringAvatar shape. Accepted values: square, circle. Default is square
businessMessageobjectCustomizes the appearance of agent/business message bubbles
businessMessage.bubbleMaxWidthnumberMaximum width of the bubble as a percentage (range: 10–100). Default is responsive breakpoints
businessMessage.hideBubblebooleanIf true, hides the bubble background behind the message text. Default is false
businessMessage.botobjectCustomizes message bubbles for bots and AI agents
businessMessage.bot.hideBubblebooleanIf set, overrides businessMessage.hideBubble for messages from bots and AI agents
businessMessage.humanAgentobjectCustomizes message bubbles for human agents
businessMessage.humanAgent.hideBubblebooleanIf set, overrides businessMessage.hideBubble for messages from human agents
userMessageobjectCustomizes the appearance of end-user message bubbles
userMessage.bubbleMaxWidthnumberMaximum width of the bubble as a percentage (range: 10–100). Default is responsive breakpoints
userMessage.hideBubblebooleanIf true, hides the bubble background behind the message text. Default is false
citationsobjectCustomizes how cited sources are presented on AI agent messages
citations.sourcesstringSpecifies how cited sources are presented. Accepted values: button, bulletedList, numberedList. Default is button.

button displays the Sources button and sources sheet.
bulletedList and numberedList render the cited sources as an inline list at the end of the message and replace the Sources button and the sources sheet entirely.
headerobjectCustomizes the message log header
header.hideAvatarbooleanIf true, hides the avatar in the message log header. Default is false
endConversationOptionobjectCustomizes the End conversation option
endConversationOption.positionstringControls where the End conversation option is displayed. Accepted values: auto, headerRight, overflowMenu. Default is auto.

auto displays End conversation as a standalone button in the header in floating mode, and in the overflow menu (three dots) in full-screen mode (mobile devices).
headerRight always displays End conversation as a standalone button on the right side of the header, in both floating and full-screen modes.
overflowMenu always displays End conversation in the overflow menu (three dots).
privacyNoticestringControls where the privacy notice is displayed in the message log. Accepted values: top, bottom. Default is top.

top displays the privacy notice at the top of the message log. With a privacy notice URL, the text is "This chat is recorded using a cloud service and is subject to the terms of our Privacy Notice." with a link on "Privacy Notice". Without a URL, the text is "This chat is recorded using a cloud service."
bottom displays the privacy notice below the composer. With a privacy notice URL, the text is "Privacy Notice applies." with a link on "Privacy Notice". Without a URL, the text is "This chat is recorded using a cloud service."
aiDisclaimerPositionstringControls how the AI disclaimer is displayed in the message log. Accepted values: author, footer. Default is author.

author displays an AI badge next to the AI agent's name on messages from the AI agent.
footer hides the AI badge and displays "AI can sometimes make mistakes. Review answers and references carefully." below the composer for the whole conversation, including after a human agent joins. The text can't be customized.

Note: If messageLog.hideHeader (or common.hideHeader) is true, the entire message log header is hidden, including the End conversation option. Any messageLog.header and endConversationOption settings are ignored.

Note: Author-specific businessMessage.bot.hideBubble and businessMessage.humanAgent.hideBubble values take precedence over businessMessage.hideBubble. If an author-specific value isn't set, it inherits businessMessage.hideBubble. Updating the global value doesn't reset an existing author-specific value.

Note: Typing indicator bubbles use businessMessage.hideBubble. The author-specific businessMessage.bot.hideBubble and businessMessage.humanAgent.hideBubble settings don't affect typing indicators because typing activity doesn't identify whether the author is a bot or human agent.

Note: When messageLog.privacyNotice is bottom and messageLog.aiDisclaimerPosition is footer, the privacy notice is displayed first, followed by the AI disclaimer.


  • preConversation

Object. Optional parameter. Settings that customize the pre-conversation page. To enable the pre-conversation page, use the Set Behavior API (messageLog.preConversation.enabled).

PropertyTypeDescription
privacyNoticestringControls where the privacy notice is displayed on the pre-conversation page. Accepted values: top, bottom. Default is bottom (below the composer).

The text for each value is the same as for messageLog.privacyNotice. This setting is independent of messageLog.privacyNotice: setting one does not change the other.

Note: When the AI disclaimer is enabled, the pre-conversation page always displays "AI can sometimes make mistakes. Review answers and references carefully." below the composer, whatever the value of messageLog.aiDisclaimerPosition.


Validation: If messageLog.privacyNotice, messageLog.aiDisclaimerPosition, or preConversation.privacyNotice has a value that is not accepted, the whole customization payload is rejected and an error is logged in the console.


  • 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 is 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 is 16
offset.web.verticalnumberVertical distance from the bottom of the screen, in pixels. Default is 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 is 16
offset.mobile.verticalnumberVertical distance from the bottom of the screen, in pixels. Default is 16

Examples

Full customization example:

zE("messenger:set", "customization", {  theme: {    primary: "#FE5E41",    onPrimary: "#FFFFFF",    message: "#F3C178",    onMessage: "#5F0F00",    action: "#B0DB43",    onAction: "#000000",    businessMessage: "#fff",    onBusinessMessage: "#F10404",    card: "#FFF4E6",    onCard: "#5F0F00",    input: "#FFFFFF",    onInput: "#5F0F00",    elevated: "#FFF8F0",    onElevated: "#5F0F00",    success: "#2E7D32",    onSuccess: "#FFFFFF",    background: "#DFE0E2",    onBackground: "#F10404",    conversationListBackground: "#1F1F1F",    onConversationListBackground: "#FFFFFF",    error: "#FF1744",    onError: "#FFFFFF",    notify: "#FF007F",    onNotify: "#FFFFFF",    onSecondaryAction: "#000000",  },  common: {    contentScale: 110,    hideHeader: false,    stylingPreset: "minimalistic"  },  conversationList: {    hideNewConversationButton: true,    hideHeader: false,    avatar: {      hidden: false,      size: 24,      shape: "circle"    },    hideTimestamp: true,    hideMessagePreview: true,    hideDivider: true,    groupByTimestamp: true  },  messageLog: {    hideHeader: false,    header: {      hideAvatar: true    },    endConversationOption: {      position: "headerRight"    },    avatar: {      position: "top",      size: 24,      shape: "circle"    },    businessMessage: {      bubbleMaxWidth: 80,      hideBubble: true    },    userMessage: {      bubbleMaxWidth: 60,      hideBubble: true    },    citations: {      sources: "bulletedList"    }  },  position: {    side: "right",    offset: {      web: { horizontal: 16, vertical: 16 }    }  }})

Theme customization:

zE("messenger:set", "customization", {  theme: {    primary: "#FE5E41",    onPrimary: "#FFFFFF",    message: "#F3C178",    onMessage: "#5F0F00",    action: "#B0DB43",    onAction: "#000000",    businessMessage: "#fff",    onBusinessMessage: "#F10404",    card: "#FFF4E6",    onCard: "#5F0F00",    input: "#FFFFFF",    onInput: "#5F0F00",    elevated: "#FFF8F0",    onElevated: "#5F0F00",    success: "#2E7D32",    onSuccess: "#FFFFFF",    background: "#DFE0E2",    onBackground: "#F10404",    error: "#FF1744",    onError: "#FFFFFF",    notify: "#FF007F",    onNotify: "#FFFFFF",    onSecondaryAction: "#000000",    conversationListBackground: "#1F1F1F",    onConversationListBackground: "#FFFFFF"  }})

Hide header globally:

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

Adjust content scale:

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

Apply the minimalistic styling preset:

zE("messenger:set", "customization", {  common: {    stylingPreset: "minimalistic"  }})

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 }    }  }})

Customize message bubbles:

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

Customize conversation list:

zE("messenger:set", "customization", {  conversationList: {    hideNewConversationButton: true,    avatar: {      hidden: false,      size: 24    },    hideTimestamp: false,    hideMessagePreview: false,    hideDivider: true,    groupByTimestamp: true  }})

Customize avatar:

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

Present cited sources as an inline list:

zE("messenger:set", "customization", {  messageLog: {    citations: {      sources: "bulletedList"    }  }})

Use "numberedList" for a numbered list, or "button" (the default) to display the Sources button and sources sheet.


Simplify the message log header:

zE("messenger:set", "customization", {  messageLog: {    header: {      hideAvatar: true    },    endConversationOption: {      position: "overflowMenu"    }  }})

This hides the avatar in the message log header and moves the End conversation action into the overflow menu (three dots), for a minimal header experience while keeping the header itself visible.


Display the privacy notice and AI disclaimer below the composer:

zE("messenger:set", "customization", {  messageLog: {    privacyNotice: "bottom",    aiDisclaimerPosition: "footer"  },  preConversation: {    privacyNotice: "bottom"  }})

This displays the privacy notice below the composer on both the pre-conversation page and the message log, and replaces the AI badge in the message log with the AI disclaimer text below the composer.


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
attachmentsFile[]NoFiles to send with the initial message. Only one File is supported

When message and attachments are 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'. To send a file, use conversationOptions.attachments.
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.

Attachments

When attachments contains a file, the file and the message text (if any) are sent together as the first message of the conversation. To start a conversation with only a file, omit message. When attachments is omitted or empty, the conversation is created with a text-only initial message, or without an initial message.

  • attachments must be an array containing exactly one File.
  • The file must be 50 MB or less. Any file type is accepted.
  • Attachments must be enabled in Admin Center.

The attachments are checked before the conversation is created. If the check fails, the conversation is not created, errorCallback receives an error with one of the attachment reasons below, and no error banner is displayed in the widget.

errorCallback receives null as soon as the conversation is created, before the file upload finishes. If the upload then fails, the first message is displayed as failed in the message log and errorCallback is not called again. The end user can retry the upload, except when the server does not support the file type.

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.
Invalid attachmentsattachments is not an array, or attachments are enabled in Admin Center and the array contains more than one item or an item that is not a browser File object.
File too largeThe file is larger than 50 MB
Attachments disabledattachments is a non-empty array and attachments are disabled in Admin Center. Returned before the number and type of items are checked

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 conversation with an initial message and a file:

const fileInput = document.querySelector("#order-receipt")
zE("messenger:ui", "newConversation", {  displayName: "Support Chat",  message: {    content: {      type: "text",      text: "Here is the receipt for order #12345"    }  },  attachments: [fileInput.files[0]]},function (error) {  if (error) {    console.error(`Conversation creation failed: ${error.reason} - ${error.message}`)  } else {    console.log("Conversation created successfully")  }})

The text and the file are sent together as the first message, and the widget navigates to the message log of the new conversation.

Show Pre-Conversation (UI)

zE('messenger:ui', 'preConversation', preConversationOptions<object>, errorCallback<function>);

Shows the pre-conversation page in the message log without creating a conversation. The conversation is created when the end user sends a message or selects a prompt.

Use this API when you want to show the pre-conversation page from your UI (for example, from a custom button).

Note: The pre-conversation page must be enabled with the Set Behavior API (messageLog.preConversation.enabled).

Parameters

  • preConversationOptions: Object. Optional parameter. Configuration for the pre-conversation page.

    PropertyTypeRequiredDescription
    displayNamestringNoTitle of the conversation created from the pre-conversation page. Must be a non-empty string

Error Callback

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

  • null, indicating the pre-conversation page was shown successfully
  • An instance of PreConversationError which contains information about why the pre-conversation page could not be shown

The PreConversationError class has the following properties:

NameTypeDescription
messagestringA descriptive message that explains the error
reasonstringProvides additional details on the cause of the pre-conversation failure
typestringIdentifies the error type as PreConversationError

Possible Error Reasons

ReasonDescription
Invalid configurationOne or more options in preConversationOptions failed validation
Pre-conversation disabledThe pre-conversation page is not enabled with the Set Behavior API
Widget not initializedThe messaging Web Widget has not finished initializing
Conversation creation in progressA conversation is already being created
Conversations not loadedThe end user's existing conversations have not loaded yet
Conversation limit reachedThe end user already has a conversation and multi-conversation mode is not enabled

Examples

Show pre-conversation page with default settings:

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

Show pre-conversation page with display name:

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

Show pre-conversation page with error callback:

zE("messenger:ui", "preConversation",  { displayName: "Support Chat" },  function (error) {    if (error) {      console.error("Failed to show pre-conversation page:", error.reason, error.message)    } else {      console.log("Pre-conversation page shown successfully")    }  })

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
    attachmentsFile[]NoFiles to send with the initial message. Only one File is supported

    When message and attachments are 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.contentobjectYes, unless conversationOptions.attachments contains a fileThe content of the initial message
    message.content.typestringYesMust be 'text'. To send a file, use conversationOptions.attachments
    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.

    Attachments

    When attachments contains a file, the file, the message text (if any), and message.metadata (if any) are sent together as the first message of the conversation. To start a conversation with only a file, omit message, or pass a message with metadata and no content. A message without content is only accepted when attachments contains a file. When attachments is omitted or empty, the conversation is created with a text-only initial message, or without an initial message.

    • attachments must be an array containing exactly one File.
    • The file must be 50 MB or less. Any file type is accepted.
    • Attachments must be enabled in Admin Center.

    The attachments are checked before the conversation is created. If the check fails, the conversation is not created, the callback receives an error with one of the attachment reasons below, and no error banner is displayed in the widget.

    The callback receives the created conversation as soon as it is created, before the file upload finishes. If the upload then fails, the first message is displayed as failed in the message log and the callback is not called again. The end user can retry the upload, except when the server does not support the file type.

  • 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 //One of: 'Invalid configuration', 'Conversation creation failed', 'Invalid attachments', 'File too large', 'Attachments disabled'  message: string //A descriptive error message}

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
Invalid attachmentsattachments is not an array. When attachments are enabled in Admin Center, also when attachments contains more than one item or an item that is not a File
File too largeThe file is larger than 50 MB
Attachments disabledattachments is a non-empty array and attachments are disabled in Admin Center. Returned before the number and type of items are checked

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)  })

Create conversation with a file only:

const fileInput = document.querySelector("#order-receipt")
zE(  "messenger",  "newConversation",  {    displayName: "Order receipt",    message: {      metadata: { orderId: "12345" }    },    attachments: [fileInput.files[0]]  },  (error, conversation) => {    if (error) {      console.error("Failed:", error.reason)      return    }    console.log("Created:", conversation.id)  })

The file is sent with the message metadata as the first message. The widget does not navigate to the new conversation.

Handle attachment errors:

const fileInput = document.querySelector("#issue-recording")
zE(  "messenger",  "newConversation",  {    message: {      content: { type: "text", text: "Here is a recording of the issue" }    },    attachments: [fileInput.files[0]]  },  (error, conversation) => {    if (error) {      if (error.reason === "File too large") {        alert("Files must be 50 MB or less.")      } else if (error.reason === "Attachments disabled") {        console.warn("Attachments are disabled in Admin Center.")      } else {        console.error(`${error.reason}: ${error.message}`)      }      return    }    console.log("Created:", conversation.id)  })

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
    contentobjectYes, unless attachments contains a fileThe content of the message
    content.typestringYesMust be 'text'. To send a file, use attachments
    content.textstringYesThe message text. Must be a non-empty, non-whitespace string
    metadataobjectNoFlat key/value pairs of message-level metadata (string, number, or boolean). Sent with the file when attachments contains a file
    attachmentsFile[]NoFiles to send with the message. Only one File is supported

    Attachments

    When attachments contains a file, the file, the content text (if any), and metadata (if any) are sent together as one message. To send only a file, omit content. When attachments is omitted or empty, a text-only message is sent.

    • attachments must be an array containing exactly one File.
    • The file must be 50 MB or less. Any file type is accepted.
    • Attachments must be enabled in Admin Center.

    The attachments are checked before anything is uploaded. If the check fails, nothing is uploaded or sent, the callback receives an error with one of the attachment reasons below, and no error banner is displayed in the widget. If the upload fails (for example, a network error or a file type the server does not support), the callback receives an error with the Message send failed reason, and the message is displayed as failed in the message log.

  • 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', 'Invalid attachments', 'File too large', 'Attachments disabled'  message: string //A descriptive error message}

Possible Error Reasons

ReasonDescription
Invalid messagemessage is missing or failed validation, or content is missing and attachments does not contain a file
Invalid conversationIdconversationId is missing, not a string, or an empty or whitespace-only string
No userNo user exists yet, so the message can't be sent
Conversation not foundNo conversation with the given conversationId exists
Message send failedThe message or file could not be sent
Invalid attachmentsattachments is not an array. When attachments are enabled in Admin Center, also when attachments contains more than one item or an item that is not a File
File too largeThe file is larger than 50 MB
Attachments disabledattachments is a non-empty array and attachments are disabled in Admin Center. Returned before the number and type of items are checked

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. For a message with a file, the time the message was sent}

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.receivedAt * 1000))    console.log("Full response:", message)  })

Send a message with text and a file:

const fileInput = document.querySelector("#order-receipt")
zE(  "messenger",  "sendMessage",  {    content: { type: "text", text: "Here is the receipt for my order." },    metadata: { orderId: "67890" },    attachments: [fileInput.files[0]]  },  "12345",  (error, message) => {    if (error) {      console.error("sendMessage failed", error.reason)      return    }    console.log("sent message id", message.id)  })

Send a file only:

zE(  "messenger",  "sendMessage",  {    attachments: [fileInput.files[0]]  },  "12345",  (error, message) => {    if (error) {      console.error("sendMessage failed", error.reason)      return    }    console.log("sent message id", message.id)  })

Handle attachment errors:

zE(  "messenger",  "sendMessage",  {    content: { type: "text", text: "Here is a recording of the issue." },    attachments: [fileInput.files[0]]  },  "12345",  (error, message) => {    if (error) {      if (error.reason === "File too large") {        alert("Files must be 50 MB or less.")      } else {        console.error(`${error.reason}: ${error.message}`)      }      return    }    console.log("sent message id", message.id)  })

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
sourcesobjectSources cited configuration. Optional. When omitted, the sources sheet opens as a modal in the message log, the same as in floating mode

Each of widget, conversationList, messageLog, and sources accepts a targetElement property — a CSS selector or element id that specifies where the component should be rendered.

The sources object also accepts:

PropertyTypeDescription
targetElementstringCSS selector or element id of the container where the Web Widget renders cited sources when the end user clicks the Sources button
eventOnlybooleanWhen false (default), clicking Close hides the sources view. When true, clicking Close fires the sourcesClosed event and does not hide the sources view. The host page is responsible for hiding the container.

Note: In embedded mode, your configuration must include at least one of the following: widget, conversationList, or messageLog. sources is additional and cannot be the only embedded configuration. If messageLog.citations.sources is set to bulletedList or numberedList, cited sources render inline in the message instead, and the Sources button and sources sheet are not used.

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, messageLog, or sources is not an object, or sources.eventOnly is not a boolean
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"  }})

Sources cited in a dedicated container:

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

When the end user clicks the Sources button, cited sources open in #sources-container instead of as a modal. Clicking a source opens it in a new browser tab.

Emit close without dismissing sources (eventOnly):

zE("messenger", "render", {  mode: "embedded",  widget: {    targetElement: "#my-messenger-container"  },  sources: {    targetElement: "#sources-container",    eventOnly: true  }})
zE("messenger:on", "sourcesClosed", function (event) {  document.querySelector("#sources-container").hidden = true})

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.