React Native Chatbot SDK

View Release Notes →

dialogs_chatbot_reactnative embeds a fully functional EnableX Dialogs chatbot into any React Native application on iOS and Android. It uses a dual-path communication architecture — a single EnxWebViewBridge class detects the platform at runtime and routes all communication accordingly: a native WKWebView bridge module on iOS, and a hidden react-native-webview on Android.

React Native Chatbot SDK v1.0.0  ·  Released June 25, 2026

First release of the React Native Chatbot SDK, published on npm. See Release Notes for what's included.

  View on NPM
Architecture

Architecture Overview

Your app renders EnxChatWidget (or EnxChatScreen) and, optionally, owns an EnxChatController. Below the controller, a single EnxWebViewBridge class checks at runtime whether Platform.OS === 'ios' and the native EnxChatBridge module is available, and routes all traffic to the iOS native path or the Android WebView path. Click any diagram on this page to open it at full size.

Layered architecture: the host app passes config, controller and props to the UI layer (EnxChatWidget, EnxChatScreen, ChatList, MessageCell, InputBar), which subscribes to EnxChatController, which drives EnxWebViewBridge. The bridge uses the native EnxChatBridge module on iOS or a hidden react-native-webview on Android, and both talk to the EnableX Dialogs bot server over HTTPS.
Green = this SDK, blue = your app and the bot server.
LayerResponsibility
UI layerEnxChatWidget (embeddable) and EnxChatScreen (full screen with a header), built from ChatList, MessageCell, InputBar, ChatMarkdown and TypingBubble. The widget also hosts the connection banner and the video call overlay.
ControllerEnxChatController holds messages, connection status and bot info, removes echoed user messages, and notifies subscribers and your callbacks. It works with any state management (useState, Redux, Zustand and so on).
BridgeEnxWebViewBridge hides the platform differences: native module calls and NativeEventEmitter on iOS, injectJavaScript and onMessage on Android.

Calls run in a WebView. When the bot starts an audio or video session, the SDK opens the video room URL in a full-screen WebView (Android) or a native WKWebView screen (iOS). For native EnableX calling with a full native call screen and click-to-call handoff, use the React Native Chatbot UI Kit.

Platform differences

ConcerniOSAndroid
WebView ownerNative EnxChatBridge modulereact-native-webview
Events inboundNativeEventEmitter → handleNativeEvent()WebView.onMessage → onMessage()
Events outboundNativeModules.EnxChatBridge.<method>()webView.injectJavaScript()
JS injectionWKUserScript at document startinjectedJavaScriptBeforeContentLoaded
console.log routingwindow.webkit.messageHandlers.chatCallbackwindow.ReactNativeWebView.postMessage()
PermissionsInfo.plist usage descriptionsAndroidManifest.xml + runtime requests
Video callNative WKWebView view controller, shown modally (openVideoCall(url))Full-screen Modal with a WebView
Video call closeNativeModules.EnxChatBridge.closeVideoCall()Modal hidden
Keyboard handlingLayoutAnimation with paddingKeyboardAvoidingView (padding behaviour)

Sequence Diagrams

Connecting & messaging

From the widget mounting to the chat being ready, then one user message and the bot's reply.

Sequence diagram: the widget calls initialize on the controller, the bridge loads the chat page with botId and host, the page reports chatReady and connected, status becomes Connected and the app gets onStatusChanged and onBotInfoReceived. Then sendText adds the user message, fires onMessageSent, goes through the bridge to sendMessageToBot, and the reply comes back as typing and message events, is parsed by parseBridgeMessage and reaches the app as onMessageReceived.
Solid arrows are direct calls; dashed arrows are asynchronous events. Messages sent before the chat is ready are queued and sent once it is. The chat page echoes each user message back; the controller drops the echo so it is not shown twice.

Bot-initiated video call

From the bot starting a call to the call ending.

Sequence diagram: the chat page sends audio_video_action start with an iFrameURL, extractVideoCallUrl builds the room URL, the controller fires onVideoCallRequest and the widget opens the call: on Android it requests camera and microphone and shows a full-screen Modal WebView, on iOS it calls openVideoCall for a native WKWebView screen. When the bot sends audio_video_action stop or the user closes the iOS call, onVideoCallEnd fires, the widget closes the call and onVideoCallEnded fires.
The call starts only when the bot sends audio_video_action: "start". See Audio & Video Calls to handle the URL yourself.

Project Structure

packages/
├── sdk/                               # The publishable SDK package
│   ├── src/
│   │   ├── index.ts                   # Public exports
│   │   ├── bridge.ts                  # Platform bridge (iOS + Android paths)
│   │   ├── controller.ts              # State management wrapper
│   │   ├── types.ts                   # All TypeScript types & enums
│   │   ├── hooks.ts                   # React hooks
│   │   ├── parser.ts                  # Message parsing utilities
│   │   ├── mediaPermissions.ts        # Android runtime permission helpers
│   │   ├── cachedMedia.ts             # Media caching utilities
│   │   └── components/
│   │       ├── ChatWidget.tsx         # Main widget (platform check lives here)
│   │       ├── ChatScreen.tsx         # Full-screen wrapper
│   │       ├── ChatList.tsx           # Scrollable message list
│   │       ├── MessageCell.tsx        # Individual message renderer
│   │       ├── InputBar.tsx           # Text / file input bar
│   │       ├── ChatMarkdown.tsx       # Markdown renderer
│   │       └── TypingBubble.tsx       # Animated typing indicator
│   ├── ios/
│   │   ├── EnxChatBridge.h            # ObjC protocol declarations
│   │   ├── EnxChatBridge.m            # RCTEventEmitter module (ObjC)
│   │   └── EnxChatBridge.swift        # WKWebView manager (Swift)
│   ├── dialogs_chatbot_reactnative.podspec
│   └── package.json
│
└── example/                           # Test / reference app
    ├── App.tsx
    ├── ios/
    └── android/
Setup

Installation

Requirements

RequirementVersion
React18.0 or later
React Native0.76 or later (New Architecture; the old Paper architecture is not supported)
TypeScript5.x, if your app uses TypeScript
iOS15.0 or later (see iOS Setup)
AndroidminSdkVersion 24 or later (see Gradle Configuration)

Add the SDK to Your Project

npm install dialogs_chatbot_reactnative
# or
yarn add dialogs_chatbot_reactnative

Install Peer Dependencies

The SDK depends on the following packages that must be installed in your app:

npm install \
  react-native-webview \
  react-native-image-picker \
  @react-native-documents/picker \
  react-native-video \
  react-native-svg \
  react-native-markdown-display \
  lucide-react-native \
  @react-native-community/datetimepicker

Important: All of the above packages ship native code. You must run pod install on iOS and rebuild after installing them.

iOS Setup

Podfile Configuration

The SDK ships a podspec (dialogs_chatbot_reactnative.podspec). CocoaPods picks it up automatically when you reference the SDK package.

Ensure your ios/Podfile targets iOS 15.0 or later:

platform :ios, '15.0'

The podspec declares the following build settings automatically — you do not need to add these manually:

s.swift_version  = '5.0'
s.frameworks     = 'WebKit'
s.pod_target_xcconfig = {
  'DEFINES_MODULE'             => 'YES',
  'SWIFT_VERSION'              => '5.0',
  'BUILD_LIBRARY_FOR_DISTRIBUTION' => 'NO'
}
s.dependency "React-Core"

DEFINES_MODULE = YES tells Xcode to generate the <pod>-Swift.h umbrella header automatically so that EnxChatBridge.m (ObjC) can see the Swift class at build time — with no manual import required.

Bridging Header — NOT Required

Do NOT add a bridging header (YourApp-Bridging-Header.h) for this SDK.

The Swift files in this SDK do not import any React Native headers directly. All React types stay inside the ObjC file (EnxChatBridge.m). The ObjC ↔ Swift communication happens through protocols declared in EnxChatBridge.h — both sides see that header automatically through the pod's module umbrella.

Adding SWIFT_OBJC_BRIDGING_HEADER to a framework pod target causes a build error; the podspec intentionally omits it.

Adding Native Files to Xcode

If you are embedding the SDK as source files (not via CocoaPods), add the following three files to your Xcode target:

FileLanguageRole
sdk/ios/EnxChatBridge.hObjective-C HeaderProtocol declarations
sdk/ios/EnxChatBridge.mObjective-CRCT module, RCTEventEmitter
sdk/ios/EnxChatBridge.swiftSwiftWKWebView manager

Steps:

  1. In Xcode, right-click your app target folder → Add Files to “<YourApp>”.
  2. Select all three files above. Make sure “Add to targets” is checked for your app target.
  3. When Xcode asks “Would you like to configure an Objective-C bridging header?” — click Create Bridging Header only if your app already uses Swift. Leave it empty unless your app itself needs it.
  4. Xcode will add DEFINES_MODULE = YES automatically to framework targets. For an app target, verify it in Build Settings → Packaging → Defines Module is set to YES.

Info.plist Permissions

Add the following keys to your app's ios/<YourApp>/Info.plist. The SDK reads camera, microphone, and location through the WKWebView (for video calls and chat geolocation features).

<!-- Camera — required for video calls and image/video file uploads -->
<key>NSCameraUsageDescription</key>
<string>Camera is used for video calls with the support agent.</string>

<!-- Microphone — required for audio and video calls -->
<key>NSMicrophoneUsageDescription</key>
<string>Microphone is used for audio and video calls with the support agent.</string>

<!-- Location — optional; needed if the chat page uses geolocation -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location may be used when the chat page requests it (e.g. maps or regional features).</string>

<!-- Photo library — required to attach images from the library -->
<key>NSPhotoLibraryUsageDescription</key>
<string>Photo library access lets you attach images in chat.</string>

<!-- Photo library (add) — only if your flow saves images to the library -->
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Lets you save images from the chat.</string>

Without these keys the app will crash with a privacy usage description exception the first time the WKWebView requests the hardware.

App Transport Security

The chat widget loads https://voiceassist.enablex.io over TLS. No ATS exceptions are required for this host.

If your organisation restricts ATS with NSAllowsArbitraryLoads = false (recommended), your Info.plist should look like:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <false/>
    <key>NSAllowsLocalNetworking</key>
    <true/>
</dict>

Running pod install

cd ios
pod install --repo-update
cd ..

Then open YourApp.xcworkspace (not .xcodeproj) and build.

Android Setup

Android uses a standard React Native WebView component — there are no native Android files to add. All communication goes through the WebView's postMessage / injectJavaScript bridge.

AndroidManifest.xml Permissions

Add the following inside the <manifest> tag of android/app/src/main/AndroidManifest.xml:

<!-- Network access — required for loading the chat page -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Camera — required for video calls and media uploads -->
<uses-permission android:name="android.permission.CAMERA" />

<!-- Audio — required for audio and video calls -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

<!-- Location — optional; required if chat page uses geolocation -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<!-- Media pickers — images on Android 13+, files on Android 12 and below -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
                 android:maxSdkVersion="32" />

<!-- Hardware feature declarations (android:required="false" keeps the app
     installable on devices without a camera / mic) -->
<uses-feature android:name="android.hardware.camera"     android:required="false" />
<uses-feature android:name="android.hardware.microphone" android:required="false" />

Runtime permissions for camera, microphone, and location are requested automatically by the SDK (mediaPermissions.ts) when the user triggers a relevant action inside the chat widget. You do not need to request them yourself.

Gradle Configuration

No custom Gradle changes are required beyond what react-native-webview and the other peer dependencies install automatically.

Ensure your android/build.gradle references the correct React Native version:

// android/build.gradle
buildscript {
    ext {
        minSdkVersion    = 24
        compileSdkVersion = 35
        targetSdkVersion  = 35
    }
}
Usage

Basic Usage

import React from 'react';
import { SafeAreaView } from 'react-native';
import { EnxChatWidget } from 'dialogs_chatbot_reactnative';

export default function App() {
  return (
    <SafeAreaView style={{ flex: 1 }}>
      <EnxChatWidget
        config={{
          botId: 'YOUR_BOT_ID',
          host:  'https://dialogs.enablex.io',
        }}
      />
    </SafeAreaView>
  );
}

When you pass only config, the widget creates its own EnxChatController, initialises it on mount and disposes it on unmount.

Full screen with a header — EnxChatScreen

EnxChatScreen wraps EnxChatWidget with a header bar (title and an optional back button). It takes every EnxChatWidget prop plus title and onBack.

import { EnxChatScreen, mobileClassicTheme } from 'dialogs_chatbot_reactnative';

export default function SupportScreen({ navigation }) {
  return (
    <EnxChatScreen
      title="Customer Support"
      onBack={() => navigation.goBack()}
      config={{ botId: 'YOUR_BOT_ID', host: 'https://dialogs.enablex.io' }}
      theme={mobileClassicTheme}
    />
  );
}

Controller Pattern (Advanced)

Use EnxChatController directly when you need to:

  • Keep chat state alive across screen navigation (the controller lives outside the widget).
  • Access messages, connection status, or bot info from outside the widget.
  • Dispose the session manually on logout.
import React, { useEffect, useRef } from 'react';
import { EnxChatController, EnxChatWidget, mobileClassicTheme } from 'dialogs_chatbot_reactnative';

export default function ChatScreen() {
  // Create the controller once and hold it in a ref so it survives re-renders.
  const controllerRef = useRef(
    new EnxChatController({
      botId: 'YOUR_BOT_ID',
      host:  'https://dialogs.enablex.io',
    })
  );

  // Dispose when the user leaves the session entirely (e.g. logout).
  useEffect(() => {
    const ctrl = controllerRef.current;
    return () => { void ctrl.dispose(); };
  }, []);

  return (
    <EnxChatWidget
      controller={controllerRef.current}
      theme={mobileClassicTheme}
      showCallingOptions
      onBotInfo={(info) => console.log('Bot name:', info.name)}
      onMessageReceived={(msg) => console.log('New message:', msg)}
      onError={(msg, type) => console.error(`[${type}] ${msg}`)}
    />
  );
}

Constructor

new EnxChatController(config: EnxBotConfig)

Properties (read-only)

PropertyTypeDescription
configEnxBotConfigThe configuration passed to the constructor.
messagesEnxMessage[]All messages (user + bot), oldest first.
statusEnxConnectionStatusCurrent connection state (see connection states).
isConnectedbooleantrue when status is Connected.
isTypingbooleantrue while the bot typing indicator is shown.
botInfoRecord<string, unknown> | undefinedBot metadata received after connecting.
conversationIdstring | undefinedCurrent conversation ID, once assigned.
errorMessagestring | undefinedLast error message, if any.
bridgeEnxWebViewBridgeThe underlying platform bridge (advanced use only).

Callbacks

Assign these right after you create the controller, before it initialises, so early events such as the first status change are not missed. They fire whether or not you also pass the matching widget props.

CallbackSignatureFires when
onMessageReceived(message: EnxMessage) => voidA message is added to the conversation: a bot reply, the typing indicator or a user message.
onStatusChanged(status: EnxConnectionStatus) => voidThe connection state changes.
onError(message: string, type: string) => voidThe bridge or socket reports an error (see error types).
onBotInfoReceived(info: Record<string, unknown>) => voidBot metadata arrives after connecting.
onVideoCallRequest(url: string) => voidThe bot sends a video room URL (audio_video_action: "start").
onVideoCallEnd() => voidThe bot sends audio_video_action: "stop", or the user closes the call screen on iOS.
function createController(): EnxChatController {
  const ctrl = new EnxChatController({ botId: 'YOUR_BOT_ID', host: 'https://dialogs.enablex.io' });

  ctrl.onStatusChanged = (status) => {
    if (status === EnxConnectionStatus.Error) console.warn('Chat connection failed');
  };
  ctrl.onError = (message, type) => {
    if (type === 'file_upload_error') Alert.alert('Upload failed', 'Please try again.');
  };
  ctrl.onBotInfoReceived = (info) => console.log('Bot name:', info.name);
  return ctrl;
}

// In your component: create it once and keep it in a ref
const controllerRef = useRef<EnxChatController | null>(null);
if (!controllerRef.current) controllerRef.current = createController();

Methods

MethodSignatureDescription
initialize(): Promise<void>Starts the bridge and connects. EnxChatWidget calls it for you; call it yourself only when you drive a custom UI without the widget.
sendText(text: string): Promise<void>Sends a text message. Queued until the chat is ready.
sendChoice(choice: EnxChoice): Promise<void>Sends a single suggestion-chip selection.
sendMultiChoice(choices: EnxChoice[]): Promise<void>Sends several selected chips at once.
sendSuggestions(titles: string[], type: EnxSuggestionType): Promise<void>Sends selected suggestion titles in single or multiple mode.
sendFile(data: SendFilePayload): Promise<void>Uploads and sends a file. Queued until the chat is ready.
resetConversation(): Promise<void>Clears the conversation on the server and the local messages.
reconnect(): Promise<void>Retries the connection manually.
clearMessages(): voidClears local messages only, with no server call.
dispose(): Promise<void>Disconnects, clears listeners and resets the bridge. Call it when you own the controller.
subscribe(listener: () => void): () => voidRegisters a change listener and returns an unsubscribe function. Used by useControllerVersion.

SendFilePayload:

{
  base64: string;     // Base64 file data (empty string for document-picker files)
  fileName: string;   // File name with extension
  mimeType: string;   // MIME type, e.g. 'image/jpeg'
  localUri?: string;  // Local file path
  size?: number;      // File size in bytes
}
// Send a suggestion chip and a file programmatically
await controller.sendChoice({ title: 'Yes', value: 'yes' });
await controller.sendFile({
  base64: imageBase64,
  fileName: 'receipt.jpg',
  mimeType: 'image/jpeg',
  size: 102400,
});

Audio & Video Calls

The SDK supports two ways to start a call. In both, the call itself runs in a WebView; for a native EnableX call screen, use the React Native Chatbot UI Kit.

Bot-initiated calls (automatic)

No code is needed. When the bot sends audio_video_action: "start" with a room URL, the widget:

  • Android: requests camera and microphone (requestCameraAndMicrophoneForMedia()), then opens the room in a full-screen Modal WebView.
  • iOS: opens the room in a native WKWebView screen through NativeModules.EnxChatBridge.openVideoCall(url). The system asks for camera and microphone access using your Info.plist keys.

The call closes when the bot sends audio_video_action: "stop", or when the user closes the call screen on iOS. Use the props to react to both events:

<EnxChatWidget
  config={config}
  onVideoCallRequest={(url) => analytics.track('video_call_started')}
  onVideoCallEnded={() => analytics.track('video_call_ended')}
/>

The URL passed to onVideoCallRequest is the full room URL, with landing=no and the bot's display name already added.

Call buttons in the input bar

Set showCallingOptions to show audio and video buttons in the input bar. Tapping them fires onAudioCall or onVideoCall; what happens next is up to your app.

<EnxChatWidget
  config={config}
  showCallingOptions
  onAudioCall={() => startAudioCall()}
  onVideoCall={() => startVideoCall()}
/>

The bot's clickToCall setting, if present, arrives in the bot info (onBotInfo / onBotInfoReceived), for example "videoOnly". You can use it to decide which call buttons to offer.

Custom UI with useControllerVersion

To build your own chat UI instead of EnxChatWidget, own an EnxChatController, call initialize() yourself, and subscribe your components with useControllerVersion.

function useControllerVersion(controller: EnxChatController): number

The hook re-renders the component whenever the controller's state changes and returns an increasing version number. The value itself has no meaning; only the change does.

import { useControllerVersion, EnxChatController } from 'dialogs_chatbot_reactnative';

function MessageCount({ controller }: { controller: EnxChatController }) {
  useControllerVersion(controller);   // re-render on every change
  return <Text>{controller.messages.length} messages</Text>;
}

You can reuse the SDK's building blocks in a custom layout: ChatList, MessageCell, InputBar, ChatMarkdown and TypingBubble are all exported. See Sub-components.

On Android the chat runs inside the hidden WebView that EnxChatWidget renders. A fully custom UI on Android must still render that WebView; see EnxWebViewBridge.

Configuration

Props Reference

EnxChatWidget Props

PropTypeDefaultDescription
configEnxBotConfig—Required when controller is not provided
controllerEnxChatController—Use an external controller instance
themePartial<EnxChatTheme>defaultThemeVisual theming overrides
showCallingOptionsbooleanfalseShow audio/video call buttons in the input bar
proactiveLocationPermissionbooleanfalseAndroid only: request location permission on mount
onMessageReceived(msg: EnxMessage) => void—Called for every incoming bot message
onMessageSent(msg: EnxMessage) => void—Called after user sends a message
onBotInfo(info: Record<string, unknown>) => void—Called when bot info is received
onError(message: string, type: string) => void—Called on connection or JS errors
onAudioCall() => void—Called when user taps the audio call button
onVideoCall() => void—Called when user taps the video call button
onVideoCallRequest(url: string) => void—Called when the bot sends a video-room URL
onVideoCallEnded() => void—Called when the call closes: the bot sent audio_video_action: stop, or the user closed the call screen on iOS

EnxChatScreen Props

All EnxChatWidget props, plus:

PropTypeDefaultDescription
titlestring"EnX Support"Header title text
onBack() => void—Shows a back button and calls this when it is tapped

EnxBotConfig Object

interface EnxBotConfig {
  botId:    string;           // EnableX bot identifier
  host:     string;           // API host, e.g. 'https://dialogs.enablex.io'
  rootPath?: string;          // Optional path prefix
  callingEnabled?: boolean;   // Enables audio/video calling
}
FieldTypeRequiredDescription
botIdstringYesBot identifier from the EnableX Dialogs dashboard.
hoststringYesDialogs service base URL, e.g. https://dialogs.enablex.io.
rootPathstringNoURL path prefix added to host. Set it only if your EnableX deployment guide specifies one.
callingEnabledbooleanNoEnables audio/video calling. Set it only if your EnableX deployment guide specifies it.

Theming

import { EnxChatWidget, mobileClassicTheme } from 'dialogs_chatbot_reactnative';

<EnxChatWidget
  config={...}
  theme={{
    primaryColor:        '#075E54',  // Header, send button, etc.
    userBubbleColor:     '#DCF8C6',  // User message bubble background
    botBubbleColor:      '#FFFFFF',  // Bot message bubble background
    backgroundColor:     '#ECE5DD',  // Chat list background
    userAvatarColor:     '#2196F3',  // User avatar circle colour
    botAvatarColor:      '#4CAF50',  // Bot avatar circle colour
    useMobileClassicLayout: false,   // WhatsApp-style layout when true
  }}
/>

Built-in themes exported from the package. A partial theme prop is merged onto defaultTheme.

FielddefaultThememobileClassicThemeUsed for
primaryColor#075E54#22C55EAccent: buttons, links, typing dots
userBubbleColor#DCF8C6#DDF7C7User message bubbles
botBubbleColor#FFFFFF#FFFFFFBot message bubbles
backgroundColor#ECE5DD#F2EEEAChat list background
userAvatarColor#2196F3#2EA3F2User avatar
botAvatarColor#4CAF50#4CAF50Bot avatar
useMobileClassicLayoutfalsetrueCompact classic mobile layout

Data Types & Enums

Import everything from the package root, for example import { EnxMessageType, EnxConnectionStatus } from 'dialogs_chatbot_reactnative';

EnxMessage

One message in the conversation. Every message the controller stores or passes to a callback has this shape.

FieldTypeDescription
idstring?Server-assigned message ID; undefined for local messages.
senderEnxMessageSenderUser or Bot.
typeEnxMessageTypeContent type.
timestampDateWhen the message was created.
textstring?Body text (markdown).
subtitlestring?Secondary line below the title.
displayStyle'default' | 'systemCentered'systemCentered renders a centered system notice (handover, agent assigned and so on) instead of a bubble.
handoverStatusstring?Handover state from the bot payload, e.g. "transfer_initiated".
mediaEnxMedia?Attached image, video or file.
linkCardEnxLinkCard?Rich link preview shown instead of a raw URL.
choicesEnxChoice[]?Suggestion chips.
actionsEnxAction[]?Action buttons.
suggestionTypeEnxSuggestionType?Single or multiple selection for choices.
controller.onMessageReceived = (msg) => {
  if (msg.sender !== EnxMessageSender.Bot) return;
  switch (msg.type) {
    case EnxMessageType.Text:  console.log('Text:', msg.text); break;
    case EnxMessageType.Image: console.log('Image:', msg.media?.url); break;
    case EnxMessageType.Suggestion:
      console.log('Chips:', msg.choices?.map((c) => c.title));
      break;
  }
  if (msg.linkCard) console.log('Link card:', msg.linkCard.title);
};

EnxMedia, EnxLinkCard, EnxChoice, EnxAction

interface EnxMedia {
  url?: string;          // Remote URL
  fileName: string;      // File name with extension
  mimeType: string;      // e.g. 'image/png'
  localUri?: string;     // Local path, for files the user sent
  size?: number;         // Size in bytes
}

interface EnxLinkCard {
  url: string;
  imageUrl?: string;
  title?: string;
  description?: string;
  buttonTitle?: string;  // Default: "Visit now"
}

interface EnxChoice {
  title: string;         // Chip label
  value: string;         // Value sent to the bot
  isSelected?: boolean;  // Local selection state (multi-select)
}

interface EnxAction {
  title: string;         // Button label
  url?: string;          // Opened in the browser on tap
  action?: string;       // Custom action identifier
}

Enums

EnumMembers
EnxMessageSenderUser, Bot
EnxMessageTypeText, Action, Suggestion, Image, File, Video, Typing, Calendar (date picker)
EnxSuggestionTypeSingle (tapping a chip sends it), Multiple (the user selects several chips, then confirms)

EnxConnectionStatus

MemberMeaningSuggested UI
IdleController created; initialize() not called yet.Empty state
LoadingBridge or WebView is starting.Spinner
ConnectedChat is ready to send and receive.Show the chat
DisconnectedConnection lost; automatic recovery follows.“Disconnected” banner
ReconnectingAutomatic reconnect in progress.“Reconnecting…” indicator
ErrorUnrecoverable error or reconnect failed.Error message and a Retry button that calls reconnect()
State diagram: Idle goes to Loading on initialize; Loading goes to Connected or to Error on init failure; Connected goes to Disconnected when the socket drops; Disconnected goes to Reconnecting or to Error after max retries; Reconnecting goes back to Connected or to Error; Error goes to Loading on reconnect; Connected and Error go to Idle on dispose.
Connection states and what moves the controller between them.

Error types

The type argument of onError:

TypeMeaning
"socket_error"WebSocket connection error.
"send_error"A message could not be sent.
"file_upload_error"A file upload failed.
"bridge_error"Error in the JavaScript ↔ native / WebView bridge.
"unknown_error"Any other error.

Bot info

onBotInfo and onBotInfoReceived pass a Record<string, unknown>. The exact keys depend on your bot's configuration in EnableX Dialogs; common ones are:

KeyTypeDescription
namestringBot display name.
avatarstring?Bot avatar URL.
welcomeMessagestring?Greeting text.
clickToCallstring?Calling mode configured for the bot, e.g. "videoOnly".
Advanced

Helper Functions

All helpers are exported from the package root. EnxChatWidget already calls the ones it needs; use them directly only in custom UIs or custom call handling.

Permission helpers (Android)

FunctionDescription
requestCameraAndMicrophoneForMedia(): Promise<void>Requests CAMERA and RECORD_AUDIO together. The widget calls it before a bot-initiated call; call it yourself if you handle onVideoCallRequest with your own call screen. No-op on iOS.
requestLocationForWebView(): Promise<void>Requests ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION. Alternatively set proactiveLocationPermission on the widget. Android only.

Media caching

FunctionDescription
cachedImageSource(uri: string): ImageURISourceReturns an <Image> source that uses the HTTP cache for remote URLs.
cachedVideoSource(uri: string)Returns a react-native-video source with disk caching for remote URLs ({ uri, isNetwork?, shouldCache? }).

Message parsing

FunctionDescription
parseBridgeMessage(rawData: unknown): EnxMessage[]Converts a raw bridge payload into messages.
extractVideoCallUrl(rawData: unknown, botDisplayName?: string): string | undefinedReturns the video room URL from a bot payload, with landing=no and the bot name added.
isAudioVideoStopPayload(rawData: unknown): booleantrue if the payload contains audio_video_action: "stop".
formatMultiSuggestionWireText(values: string[]): stringFormats selected multi-select values as the JSON wire text sent to the bot, e.g. ["a","b"].

Sub-components

The pieces EnxChatWidget is built from, exported for custom layouts. They take a full EnxChatTheme (not a partial one).

ComponentDescriptionCallbacks
ChatListScrolling message list with date headers and the typing indicator. Accepts a ref of type ChatListHandle with scrollToBottom(animated: boolean).onSuggestionTap(titles, type), onActionTap(action)
MessageCellOne message bubble, for every message type and link cards.onSuggestionTap(titles, type), onActionTap(action)
InputBarText field, attachment picker (camera, gallery, files, video) and call buttons.onSendText(text), onSendFile(payload), onAudioCall(), onVideoCall()
ChatMarkdownMarkdown renderer with seven style variants (body, subtitle, title, linkTitle, linkDesc, button, compact).—
TypingBubbleAnimated three-dot typing indicator.—

EnxWebViewBridge

The platform bridge, available as controller.bridge. Most apps never call it directly; it matters only for custom UIs that replace EnxChatWidget entirely.

MemberDescription
usesNativePathtrue on iOS when the native EnxChatBridge module is available.
attachWebViewRef(ref)Android only. Attaches the hidden WebView so the bridge can inject JavaScript into it.
initializeAfterPageLoad()Android only. Call from the WebView's onLoadEnd.
initializeNative()iOS only. Starts the native bridge module.
resetWebViewSession()Resets bridge state so the next mount starts cleanly.

Bridge events

Every event from the chat page reaches the controller through the bridge as an { event, data } envelope:

EventDataController action
chatReady—Sends any queued messages
connected / reconnected—status = Connected
disconnected—status = Disconnected
reconnecting—status = Reconnecting
conversationReady{ conversationId }Stores the conversation ID
messageArray of message payloadsParses and adds the messages
typing{ timeInMs }Shows the typing indicator
clear{ conversationId? }Clears the messages
error{ message, type }Sets the error state and fires onError
botInfoBot metadataStores botInfo and fires onBotInfoReceived

Platform Communication Flow

iOS — Inbound Event Flow

Chat web page
  └─ console.log(JSON.stringify({ event, data }))
       └─ WKUserScript override (injected at document start)
            └─ window.webkit.messageHandlers.chatCallback.postMessage(msg)
                 └─ EnxChatBridgeImpl (Swift) WKScriptMessageHandler
                      └─ eventEmitter?.emitChatEvent(dict)
                           └─ EnxChatBridge (ObjC) RCTEventEmitter
                                └─ sendEventWithName: @"EnxChatEvent"
                                     └─ NativeEventEmitter in bridge.ts
                                          └─ handleNativeEvent() → handleEnvelope()

iOS — Outbound Message Flow

User sends text/file
  └─ EnxWebViewBridge.sendText() / sendFile()
       └─ NativeModules.EnxChatBridge.sendText(text)  [JS → ObjC]
            └─ EnxChatBridge.m  RCT_EXPORT_METHOD
                 └─ [self.impl sendText:text]          [ObjC → Swift]
                      └─ EnxChatBridgeImpl.evalJS()
                           └─ WKWebView.evaluateJavaScript()
                                └─ sendMessageToBot(text, [])

Android — Inbound Event Flow

Chat web page
  └─ console.log(JSON.stringify({ event, data }))
       └─ androidBridge injection (injectedJavaScriptBeforeContentLoaded)
            └─ window.ReactNativeWebView.postMessage(jsonString)
                 └─ WebView onMessage callback in ChatWidget.tsx
                      └─ managed.bridge.onMessage(e)
                           └─ JSON.parse → handleEnvelope()

Android — Outbound Message Flow

User sends text/file
  └─ EnxWebViewBridge.sendText() / sendFile()
       └─ this.inject(`sendMessageToBot('${text}', []);`)
            └─ WebView.injectJavaScript()
                 └─ sendMessageToBot() on the chat page

Adding a New Bridge Method (iOS & Android)

When the chat page exposes a new JavaScript API (e.g. setUserContext()), follow these steps:

Step 1 — Declare the Protocol Method (iOS only)

Open sdk/ios/EnxChatBridge.h and add to the EnxChatWebViewManager protocol:

- (void)setUserContext:(NSDictionary *)context;

Step 2 — Implement in Swift (iOS only)

Open sdk/ios/EnxChatBridge.swift and add inside EnxChatBridgeImpl:

func setUserContext(_ context: [String: Any]) {
    guard let jsonData = try? JSONSerialization.data(withJSONObject: context),
          let jsonStr  = String(data: jsonData, encoding: .utf8) else { return }
    evalJS("typeof setUserContext==='function'&&setUserContext(\(jsonStr));")
}

Step 3 — Export from ObjC (iOS only)

Open sdk/ios/EnxChatBridge.m and add:

RCT_EXPORT_METHOD(setUserContext:(NSDictionary *)context) {
    [self.impl setUserContext:context];
}

Step 4 — Add to the TypeScript Bridge (both platforms)

Open sdk/src/bridge.ts and add a new public method:

async setUserContext(context: Record<string, unknown>): Promise<void> {
    if (this.usesNativePath) {
        // iOS — calls the native module method exported in Step 3
        NativeModules.EnxChatBridge.setUserContext(context);
    } else {
        // Android — injects JavaScript directly into the WebView
        const json = JSON.stringify(context).replace(/'/g, "\\'");
        this.inject(`typeof setUserContext==='function'&&setUserContext(${json});true;`);
    }
}

Step 5 — Expose from the Controller (optional)

If consumers should call this via the controller, add to sdk/src/controller.ts:

async setUserContext(context: Record<string, unknown>): Promise<void> {
    await this.bridge.setUserContext(context);
}

Step 6 — pod install

cd ios && pod install && cd ..
Feature Support

Feature Support (v1.0.0)

FeatureSupportedNotes
Full chat UIYesDrop-in EnxChatWidget with platform detection built in.
Auto-reconnectYesConfigurable reconnect status banner.
Typing indicatorYesAnimated bubble shown during bot response delay.
Text, markdown, and rich message typesYesImage, video, file, link card, single/multi-choice, action buttons, calendar, centered system notices.
Video call supportYesFull-screen WebView modal launched on audio_video_action: start; dismissed on stop or back press.
Audio/video call buttonsYesOptional input-bar UI wired to onAudioCall / onVideoCall props.
File uploadYesCamera capture, gallery picker, document picker.
ThemingYesFull colour customization via EnxChatTheme; defaultTheme and mobileClassicTheme built in.
External controllerYesEnxChatController keeps the session alive across navigation.
Message queueing before readyYesMessages sent before the chat is Ready are buffered and flushed automatically.
Objective-C / native module on iOSYesNative EnxChatBridge module (Swift + ObjC) — Android has no native module.
Offline / cache-first modeNoRequires network on every session start.
Picture-in-picture video callsNoNot supported in v1.0.
Markdown tablesNoNot supported by the markdown renderer in v1.0.
Native EnableX call screenNoCalls run in a WebView. Use the React Native Chatbot UI Kit for native calling and click-to-call handoff.

Known Limitations

LimitationImpactWorkaround
iOS and Android onlyWeb, Windows and macOS are not supported.Use the Web Chatbot SDK on the web.
iOS needs the native moduleNativeModules.EnxChatBridge must be compiled into the app.Follow iOS Setup and rebuild after pod install.
Android call screen is a WebViewThe full-screen call modal cannot be customised beyond the WebView.Handle onVideoCallRequest and open the URL in your own screen.
No offline queueMessages sent while disconnected fail silently. (Messages sent before the first connection are queued.)Watch onStatusChanged and offer a retry.
Empty base64 for document-picker filesLarge documents skip base64 encoding.Pass localUri in sendFile().
React Native 0.76 or laterThe old architecture (Paper) is not supported.Upgrade to React Native 0.76+ with the New Architecture.
Reference

Troubleshooting

iOS — EnxChatBridgeImpl class not found

Cause: The Swift file is not included in the build target, or DEFINES_MODULE is not YES.

Fix:

  1. In Xcode, select EnxChatBridge.swift → File Inspector → confirm your target is checked under Target Membership.
  2. In Build Settings, search Defines Module → set to YES.
  3. Clean build folder (Cmd+Shift+K) and rebuild.

iOS — Chat Events Never Arrive (no onReady / onConnected)

Cause: The WKWebView's chatCallback message handler was not registered, or the console.log override script failed.

Fix:

  1. Verify EnxChatBridge.swift, EnxChatBridge.m, and EnxChatBridge.h are all in the same pod/target.
  2. Check that NativeModules.EnxChatBridge is not undefined in the JS console — if it is, the native module was not linked.
  3. Confirm iOS 15.0+ deployment target (earlier versions have WKWebView restrictions).

Android — Chat Events Never Arrive (widget stuck on “Connecting…”)

Cause: The androidBridge injection script did not run before the page loaded, or onMessage was not attached.

Fix:

  1. Confirm injectedJavaScriptBeforeContentLoaded is set on the hidden WebView in ChatWidget.tsx.
  2. Check INTERNET permission is in AndroidManifest.xml.
  3. Verify the hidden WebView rendered by checking !managed.bridge.usesNativePath evaluates to true on Android (i.e., the native module is absent).

Android — Camera or Microphone Permission Denied in WebView

Cause: onPermissionRequest from WebChromeClient not handled, or the Android runtime permission was not granted.

Fix:

  1. Ensure CAMERA and RECORD_AUDIO are declared in AndroidManifest.xml.
  2. The SDK calls PermissionsAndroid.requestMultiple() automatically before a video call. If you override onVideoCallRequest, call requestCameraAndMicrophoneForMedia() from mediaPermissions.ts yourself before opening the video screen.

Chat shows only the loading spinner

Fix:

  1. Check that botId and host are correct.
  2. Log onError to see bridge or socket errors.
  3. On Android, confirm the INTERNET permission is in AndroidManifest.xml.

Messages appear twice

Cause: The SDK already drops the chat page's echo of each user message, so duplicates come from the app.

Fix: Check that your code does not call sendText() twice, and that you do not create two controllers for the same chat (for example with new EnxChatController() in a component body instead of keeping it in a ref).

File upload fails silently

Fix: Check that the MIME type matches the file extension. For document-picker files, base64 may be empty; make sure localUri is set. Watch onError for "file_upload_error".

Android — Keyboard hides the input bar

Fix: Add android:windowSoftInputMode="adjustResize" to your main activity in AndroidManifest.xml.

Pod Install Fails with Swift/ObjC Bridging Header Error

Cause: SWIFT_OBJC_BRIDGING_HEADER was manually added to the pod's xcconfig.

Fix: Remove it. The SDK does not use a bridging header for the pod target. DEFINES_MODULE = YES in the podspec is sufficient.

react-native-webview Not Found

Cause: Peer dependencies not installed.

npm install react-native-webview
cd ios && pod install && cd ..