React Native Chatbot SDK
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.
First release of the React Native Chatbot SDK, published on npm. See Release Notes for what's included.
View on NPMArchitecture 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.
| Layer | Responsibility |
|---|---|
| UI layer | EnxChatWidget (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. |
| Controller | EnxChatController 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). |
| Bridge | EnxWebViewBridge 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
| Concern | iOS | Android |
|---|---|---|
| WebView owner | Native EnxChatBridge module | react-native-webview |
| Events inbound | NativeEventEmitter → handleNativeEvent() | WebView.onMessage → onMessage() |
| Events outbound | NativeModules.EnxChatBridge.<method>() | webView.injectJavaScript() |
| JS injection | WKUserScript at document start | injectedJavaScriptBeforeContentLoaded |
| console.log routing | window.webkit.messageHandlers.chatCallback | window.ReactNativeWebView.postMessage() |
| Permissions | Info.plist usage descriptions | AndroidManifest.xml + runtime requests |
| Video call | Native WKWebView view controller, shown modally (openVideoCall(url)) | Full-screen Modal with a WebView |
| Video call close | NativeModules.EnxChatBridge.closeVideoCall() | Modal hidden |
| Keyboard handling | LayoutAnimation with padding | KeyboardAvoidingView (padding behaviour) |
Sequence Diagrams
Connecting & messaging
From the widget mounting to the chat being ready, then one user message and the bot's reply.
Bot-initiated video call
From the bot starting a call to the call ending.
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/
Installation
Requirements
| Requirement | Version |
|---|---|
| React | 18.0 or later |
| React Native | 0.76 or later (New Architecture; the old Paper architecture is not supported) |
| TypeScript | 5.x, if your app uses TypeScript |
| iOS | 15.0 or later (see iOS Setup) |
| Android | minSdkVersion 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:
| File | Language | Role |
|---|---|---|
sdk/ios/EnxChatBridge.h | Objective-C Header | Protocol declarations |
sdk/ios/EnxChatBridge.m | Objective-C | RCT module, RCTEventEmitter |
sdk/ios/EnxChatBridge.swift | Swift | WKWebView manager |
Steps:
- In Xcode, right-click your app target folder → Add Files to “<YourApp>”.
- Select all three files above. Make sure “Add to targets” is checked for your app target.
- 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.
- Xcode will add
DEFINES_MODULE = YESautomatically to framework targets. For an app target, verify it in Build Settings → Packaging → Defines Module is set toYES.
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
}
}
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)
| Property | Type | Description |
|---|---|---|
config | EnxBotConfig | The configuration passed to the constructor. |
messages | EnxMessage[] | All messages (user + bot), oldest first. |
status | EnxConnectionStatus | Current connection state (see connection states). |
isConnected | boolean | true when status is Connected. |
isTyping | boolean | true while the bot typing indicator is shown. |
botInfo | Record<string, unknown> | undefined | Bot metadata received after connecting. |
conversationId | string | undefined | Current conversation ID, once assigned. |
errorMessage | string | undefined | Last error message, if any. |
bridge | EnxWebViewBridge | The 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.
| Callback | Signature | Fires when |
|---|---|---|
onMessageReceived | (message: EnxMessage) => void | A message is added to the conversation: a bot reply, the typing indicator or a user message. |
onStatusChanged | (status: EnxConnectionStatus) => void | The connection state changes. |
onError | (message: string, type: string) => void | The bridge or socket reports an error (see error types). |
onBotInfoReceived | (info: Record<string, unknown>) => void | Bot metadata arrives after connecting. |
onVideoCallRequest | (url: string) => void | The bot sends a video room URL (audio_video_action: "start"). |
onVideoCallEnd | () => void | The 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
| Method | Signature | Description |
|---|---|---|
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 | (): void | Clears 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): () => void | Registers 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-screenModalWebView. - 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.
Props Reference
EnxChatWidget Props
| Prop | Type | Default | Description |
|---|---|---|---|
config | EnxBotConfig | — | Required when controller is not provided |
controller | EnxChatController | — | Use an external controller instance |
theme | Partial<EnxChatTheme> | defaultTheme | Visual theming overrides |
showCallingOptions | boolean | false | Show audio/video call buttons in the input bar |
proactiveLocationPermission | boolean | false | Android 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:
| Prop | Type | Default | Description |
|---|---|---|---|
title | string | "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
}
| Field | Type | Required | Description |
|---|---|---|---|
botId | string | Yes | Bot identifier from the EnableX Dialogs dashboard. |
host | string | Yes | Dialogs service base URL, e.g. https://dialogs.enablex.io. |
rootPath | string | No | URL path prefix added to host. Set it only if your EnableX deployment guide specifies one. |
callingEnabled | boolean | No | Enables 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.
| Field | defaultTheme | mobileClassicTheme | Used for |
|---|---|---|---|
primaryColor | #075E54 | #22C55E | Accent: buttons, links, typing dots |
userBubbleColor | #DCF8C6 | #DDF7C7 | User message bubbles |
botBubbleColor | #FFFFFF | #FFFFFF | Bot message bubbles |
backgroundColor | #ECE5DD | #F2EEEA | Chat list background |
userAvatarColor | #2196F3 | #2EA3F2 | User avatar |
botAvatarColor | #4CAF50 | #4CAF50 | Bot avatar |
useMobileClassicLayout | false | true | Compact 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.
| Field | Type | Description |
|---|---|---|
id | string? | Server-assigned message ID; undefined for local messages. |
sender | EnxMessageSender | User or Bot. |
type | EnxMessageType | Content type. |
timestamp | Date | When the message was created. |
text | string? | Body text (markdown). |
subtitle | string? | Secondary line below the title. |
displayStyle | 'default' | 'systemCentered' | systemCentered renders a centered system notice (handover, agent assigned and so on) instead of a bubble. |
handoverStatus | string? | Handover state from the bot payload, e.g. "transfer_initiated". |
media | EnxMedia? | Attached image, video or file. |
linkCard | EnxLinkCard? | Rich link preview shown instead of a raw URL. |
choices | EnxChoice[]? | Suggestion chips. |
actions | EnxAction[]? | Action buttons. |
suggestionType | EnxSuggestionType? | 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
| Enum | Members |
|---|---|
EnxMessageSender | User, Bot |
EnxMessageType | Text, Action, Suggestion, Image, File, Video, Typing, Calendar (date picker) |
EnxSuggestionType | Single (tapping a chip sends it), Multiple (the user selects several chips, then confirms) |
EnxConnectionStatus
| Member | Meaning | Suggested UI |
|---|---|---|
Idle | Controller created; initialize() not called yet. | Empty state |
Loading | Bridge or WebView is starting. | Spinner |
Connected | Chat is ready to send and receive. | Show the chat |
Disconnected | Connection lost; automatic recovery follows. | “Disconnected” banner |
Reconnecting | Automatic reconnect in progress. | “Reconnecting…” indicator |
Error | Unrecoverable error or reconnect failed. | Error message and a Retry button that calls reconnect() |
Error types
The type argument of onError:
| Type | Meaning |
|---|---|
"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:
| Key | Type | Description |
|---|---|---|
name | string | Bot display name. |
avatar | string? | Bot avatar URL. |
welcomeMessage | string? | Greeting text. |
clickToCall | string? | Calling mode configured for the bot, e.g. "videoOnly". |
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)
| Function | Description |
|---|---|
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
| Function | Description |
|---|---|
cachedImageSource(uri: string): ImageURISource | Returns 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
| Function | Description |
|---|---|
parseBridgeMessage(rawData: unknown): EnxMessage[] | Converts a raw bridge payload into messages. |
extractVideoCallUrl(rawData: unknown, botDisplayName?: string): string | undefined | Returns the video room URL from a bot payload, with landing=no and the bot name added. |
isAudioVideoStopPayload(rawData: unknown): boolean | true if the payload contains audio_video_action: "stop". |
formatMultiSuggestionWireText(values: string[]): string | Formats 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).
| Component | Description | Callbacks |
|---|---|---|
ChatList | Scrolling message list with date headers and the typing indicator. Accepts a ref of type ChatListHandle with scrollToBottom(animated: boolean). | onSuggestionTap(titles, type), onActionTap(action) |
MessageCell | One message bubble, for every message type and link cards. | onSuggestionTap(titles, type), onActionTap(action) |
InputBar | Text field, attachment picker (camera, gallery, files, video) and call buttons. | onSendText(text), onSendFile(payload), onAudioCall(), onVideoCall() |
ChatMarkdown | Markdown renderer with seven style variants (body, subtitle, title, linkTitle, linkDesc, button, compact). | — |
TypingBubble | Animated 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.
| Member | Description |
|---|---|
usesNativePath | true 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:
| Event | Data | Controller action |
|---|---|---|
chatReady | — | Sends any queued messages |
connected / reconnected | — | status = Connected |
disconnected | — | status = Disconnected |
reconnecting | — | status = Reconnecting |
conversationReady | { conversationId } | Stores the conversation ID |
message | Array of message payloads | Parses 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 |
botInfo | Bot metadata | Stores 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 (v1.0.0)
| Feature | Supported | Notes |
|---|---|---|
| Full chat UI | Yes | Drop-in EnxChatWidget with platform detection built in. |
| Auto-reconnect | Yes | Configurable reconnect status banner. |
| Typing indicator | Yes | Animated bubble shown during bot response delay. |
| Text, markdown, and rich message types | Yes | Image, video, file, link card, single/multi-choice, action buttons, calendar, centered system notices. |
| Video call support | Yes | Full-screen WebView modal launched on audio_video_action: start; dismissed on stop or back press. |
| Audio/video call buttons | Yes | Optional input-bar UI wired to onAudioCall / onVideoCall props. |
| File upload | Yes | Camera capture, gallery picker, document picker. |
| Theming | Yes | Full colour customization via EnxChatTheme; defaultTheme and mobileClassicTheme built in. |
| External controller | Yes | EnxChatController keeps the session alive across navigation. |
| Message queueing before ready | Yes | Messages sent before the chat is Ready are buffered and flushed automatically. |
| Objective-C / native module on iOS | Yes | Native EnxChatBridge module (Swift + ObjC) — Android has no native module. |
| Offline / cache-first mode | No | Requires network on every session start. |
| Picture-in-picture video calls | No | Not supported in v1.0. |
| Markdown tables | No | Not supported by the markdown renderer in v1.0. |
| Native EnableX call screen | No | Calls run in a WebView. Use the React Native Chatbot UI Kit for native calling and click-to-call handoff. |
Known Limitations
| Limitation | Impact | Workaround |
|---|---|---|
| iOS and Android only | Web, Windows and macOS are not supported. | Use the Web Chatbot SDK on the web. |
| iOS needs the native module | NativeModules.EnxChatBridge must be compiled into the app. | Follow iOS Setup and rebuild after pod install. |
| Android call screen is a WebView | The full-screen call modal cannot be customised beyond the WebView. | Handle onVideoCallRequest and open the URL in your own screen. |
| No offline queue | Messages sent while disconnected fail silently. (Messages sent before the first connection are queued.) | Watch onStatusChanged and offer a retry. |
Empty base64 for document-picker files | Large documents skip base64 encoding. | Pass localUri in sendFile(). |
| React Native 0.76 or later | The old architecture (Paper) is not supported. | Upgrade to React Native 0.76+ with the New Architecture. |
Troubleshooting
iOS — EnxChatBridgeImpl class not found
Cause: The Swift file is not included in the build target, or DEFINES_MODULE is not YES.
Fix:
- In Xcode, select
EnxChatBridge.swift→ File Inspector → confirm your target is checked under Target Membership. - In Build Settings, search
Defines Module→ set toYES. - 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:
- Verify
EnxChatBridge.swift,EnxChatBridge.m, andEnxChatBridge.hare all in the same pod/target. - Check that
NativeModules.EnxChatBridgeis notundefinedin the JS console — if it is, the native module was not linked. - 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:
- Confirm
injectedJavaScriptBeforeContentLoadedis set on the hiddenWebViewinChatWidget.tsx. - Check
INTERNETpermission is inAndroidManifest.xml. - Verify the hidden WebView rendered by checking
!managed.bridge.usesNativePathevaluates totrueon 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:
- Ensure
CAMERAandRECORD_AUDIOare declared inAndroidManifest.xml. - The SDK calls
PermissionsAndroid.requestMultiple()automatically before a video call. If you overrideonVideoCallRequest, callrequestCameraAndMicrophoneForMedia()frommediaPermissions.tsyourself before opening the video screen.
Chat shows only the loading spinner
Fix:
- Check that
botIdandhostare correct. - Log
onErrorto see bridge or socket errors. - On Android, confirm the
INTERNETpermission is inAndroidManifest.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 ..