# Widget Callbacks
Widget callbacks allow you to execute custom JavaScript code in response to specific events within the User.com widget such as when it loads, opens, closes, or receives a message.
# Introduction
You define callbacks directly inside the window.civchat configuration object. These functions enable deep integration between the widget and your application, allowing you to trigger Data Layer events, handle automation payloads, or log user interactions.
# Available callbacks
# onLoad
Triggered immediately after the widget script and resources have finished loading.
- Use case: Setting global variables, dispatching events to your SPA, or pushing "Widget Ready" events to Google Tag Manager.
onLoad: function() {
console.log('Widget loaded');
// Example: Notify GTM
dataLayer.push({ event: "User.com - Widget Ready" });
}
# onPayloadReceived
Triggered when the widget receives a special payload from the Send Code automation module in User.com.
- Use case: Executing remote JavaScript logic defined in your automation flows.
onPayloadReceived: function (message) {
if (typeof message === "string") {
try {
// Execute the string as code
var fn = new Function(message);
fn();
} catch (e) {
console.error("UE - error executing message:", e);
}
}
}
# onMessage
Triggered for every incoming chat message. The function receives a message object containing content and metadata.
- Key Property:
isAdmin(Boolean)true: Message sent by the Backend (Agent or Automation).false: Message sent by the User (Frontend).
onMessage: function (message) {
if (message.isAdmin) {
console.log("New message from Support:", message.content);
} else {
console.log("User sent message:", message.content);
}
}
# onOpen
Triggered when the widget is expanded (either by the user clicking the launcher or programmatically via widget.open).
onOpen: function () {
console.log("Widget opened");
// Example: Pause a video or analytics tracking
}
# onClose
Triggered when the widget is minimized/closed.
onClose: function () {
console.log("Widget closed");
}
# Example usage
Here is a complete configuration example demonstrating how to implement these callbacks within your initialization script.
window.civchat = {
apiKey: "YOUR_API_KEY",
name: "John Doe",
user_id: "52bdc3be5145e87076c8",
// 1. Trigger GTM when ready
onLoad: function () {
dataLayer.push({ event: "User.com - Widget Ready" });
},
// 2. Handle incoming messages
onMessage: function (message) {
console.log('Message received:', message.content);
if (message.isAdmin) {
// Logic for agent messages
}
},
// 3. Handle Automation "Send Code" payloads
onPayloadReceived: function (message) {
if (typeof message === "string") {
try {
var fn = new Function(message);
fn();
} catch (e) {
console.error("Execution error:", e);
}
}
},
// 4. UI State listeners
onOpen: function () {
console.log("Chat window expanded");
},
onClose: function () {
console.log("Chat window minimized");
}
};