Widget events
Set callbacks during initialization and attach page event handlers before the action whose result you need.
Callbacks and Events
SenlerWidget.init accepts:
contextProvider()— synchronously returns persistent page context; Promises are not supported;resolveRuntime(context)— synchronously selects settings based on visitor and dialog state;onCollapse(detail)— reports a click onshell.collapse_button.onReady(detail)— reports successful chat initialization and authentication once.detailcontainschannel_id,display_mode, andbutton_only. Inbutton_onlymode, this means the button is ready without loading a chat.onError(error)— reports the first startup failure for the instance; message failures and reconnects after readiness do not trigger it.
SenlerWidget.init({
channel_id: "CHANNEL_ID",
onReady(detail) {
console.log("Widget ready", detail);
},
onError(error) {
console.error(error.code, error.message, error.retryable);
if (error.diagnostics) {
console.error("Widget startup state", error.diagnostics);
}
},
});
error is an Error named SenlerWidgetInitializationError. Its code is invalid_config, iframe_load_failed, startup_failed, authentication_failed, init_failed, init_timeout, or protocol_mismatch. retryable indicates whether retrying without changing configuration may help. Startup without a result times out with init_timeout after 90 seconds; a specific failure may arrive earlier. Invalid configuration also throws the same error synchronously from init.
A chat startup error may also include diagnostics, a snapshot of the state when the failure occurred. Use it in your integration's error log. It contains:
attempt,durationMs,totalDurationMs— the attempt number and the duration of the current attempt and entire startup, in milliseconds.failureReason,loaderStage, optionallastAppStage— the failure reason and latest loader and application stages.iframeLoaded,appReady— whether the iframe and application had loaded.online,visibility— the browser's reported network state and page visibility.
The field is optional: for example, a configuration error before chat loading may omit it. This is troubleshooting data, not a readiness signal; onReady confirms successful startup.
With direct init, a temporary loading failure may recover after onError, followed by onReady. If the widget application itself reports a startup or rendering failure, it shows an error instead of loading indefinitely; retry is initiated by the user. Each callback runs at most once per instance. After destroy() or replacement through init, that instance's delayed callbacks are suppressed. Exceptions inside callbacks do not interrupt the widget.
In the SDK, createSenlerWidgetSession(...).ready waits for chat readiness. The first failure rejects the Promise and destroys the instance; create a new session or change React's retryKey to retry. Destroying a pending session rejects with AbortError. Failure to load the script itself rejects the loader/session Promise before init runs.
customActions buttons use each action's handler, not a shared callback.
Instance events
SenlerWidget.on(event, handler) subscribes to the events below. The returned function unsubscribes. Use widget.on for a separate instance.
const widget = SenlerWidget.create({ channel_id: "CHANNEL_ID" });
const unsubscribe = widget.on("messageSent", ({ source, dialogId }) => {
if (source === "widget") console.log("Message accepted", dialogId);
});
Subscribing immediately after synchronous create observes the first opening even while the iframe loads. Subscribing after readiness does not replay past events.
openandclosedescribe panel visibility transitions, including site commands. Repeatingopen()on an open panel emits nothing. An initially visible embedded widget is not an opening event.messageSentmeans the server accepted a message, including into its queue. Fields arerequestId,dialogId,source: "widget" | "api", pluseventIdorqueueId.widgetcovers the composer and greeting buttons;apicoversaskand text edits.- Sending failures, agent replies, and empty-dialog creation do not emit
messageSent. Duplicate acknowledgements are suppressed within the instance; reloading does not replay history as new events. messageReceiveddelivers a new agent or operator message:sender: "assistant" | "operator",timestamp, optionalagentId, and message data. It is not limited to yourask: use that request'sonAnsweror final Promise for a specific question.unreadCountChangedprovides the number of unread messages. If the count is already known, a subscriber receives it immediately, then whenever it changes.- The count includes all visible, non-archived dialogs, independent of history pagination. Hidden service dialogs do not emit these notifications: read their answers through
ask.messageReceivedis a live message notification, not a history recovery API after a long disconnection. destroyruns when the instance is released; its subscriptions are then removed.connectionChangedprovides the connection state:disconnected,connecting,connected,reconnecting, orerror. The subscriber receives the current state when known, then changes. This describes connectivity, not the outcome of an individual question.dialogsChangedindicates that the dialog list may have changed. It carries no list data: callgetDialogsagain with the current search and page parameters.settingsChangedindicates that settings may have changed. CallgetSettingsagain to update feature availability, credits, and the greeting.
For a custom interface, coalesce frequent dialogsChanged and settingsChanged events into one refresh of the corresponding data. Call the unsubscribe functions when removing the interface. Use subscribeDialog for history and changes in a particular dialog; messageReceived alone is insufficient.
For site analytics, distinguish message counts from visitors who started chatting. The messageSent event contains no message text or contacts and does not replace checking a successful payment or saved contact.
Page events
window event |
When it is dispatched |
|---|---|
senler-widget:collapse-request |
The user clicked the collapse button. |
senler-widget:mobile-edge-swipe |
The user completed an enabled left-edge swipe. |
senler-widget:credit-purchase-requested |
The user requested additional credits; detail contains channel_id and lead_id. |
senler-widget:stage |
A diagnostic loading, connection, sending, history, or file stage changed. Use it for observability, not business logic. |
senler-widget:stage always includes area, phase, and timestamp in detail; it may also include attempt, duration_ms, and a final result: "success" | "error" | "timeout".
area |
Possible phase values |
|---|---|
loader |
instance-created, iframe-created, iframe-loading, iframe-loaded, app-mounted, ready-timeout, error |
bootstrap |
loading, success, error, timeout, interactive |
dialogs |
idle, loading, refetching, success, empty, error |
history |
idle, loading, refetching, loading-more, success, empty, error |
realtime |
disabled, token-loading, connecting, connected, reconnecting, disconnected, error |
message |
optimistic, sending, queued, sent, failed, waiting, typing, streaming, done, error |
upload |
requesting-url, uploading, confirming, ready, error |
This is a diagnostic stream, not the final state machine of a business process. The stage set may expand and individual phases may repeat or be skipped, so business logic must not depend on their exact sequence.
See embedding in a container for collapse and swipe handling, and sending messages from a website for sending statuses.