---
title: "Web channel developer guide"
description: "Control the Moveo web channel from your page with instance methods, event listeners, and analytics events, with code examples."
---

# Web channel developer guide

> Control the Moveo web channel from your page with instance methods, event listeners, and analytics events, with code examples.

## Instance methods

The web channel exposes methods to control behavior and interact with the chat programmatically.

```javascript
MoveoAI.init({
  integrationId: "YOUR-INTEGRATION-ID",
  version: "v2",
}).then((instance) => {
  // Use instance methods here
});
```

### Window control

#### openWindow()

Opens the chat window if it is closed.

```javascript
instance.openWindow();
```

#### closeWindow()

Closes the chat window if it is open.

```javascript
instance.closeWindow();
```

### Messaging

#### sendMessage()

Programmatically send a message to the AI agent.

```javascript
instance.sendMessage({ text: "Hello, I need help" });

// Open window after sending
instance.sendMessage({ text: "Start conversation" });
instance.openWindow();
```

**Behavior:**

- If conversation exists: sends immediately
- No conversation: overrides welcome message
- With visitor form: sends after form completion

#### Run a dialog node

To start a specific dialog from your page, send the ID of an event-triggered node instead of text.
The AI agent runs that node directly, so no intent can answer in its place. Use this for actions
the visitor takes outside the chat, such as a visitor who selects a pricing link.

```javascript
instance.sendMessage({ trigger_node_id: "YOUR_NODE_ID" });
```

Send `trigger_node_id` alone, without `text`. If no conversation exists, the node starts the
conversation.

### User context

#### updateContext()

Update user information or session data dynamically.

```javascript
instance.updateContext({
  user: {
    display_name: "John Doe",
    email: "john@example.com",
  },
  customer_id: "12345",
  account_type: "premium",
});
```

### Session management

#### destroy()

End the conversation and remove the web channel from the page. `destroy()` returns a promise. Wait
for it before you call `MoveoAI.init()` again, which starts a new session.

```javascript
// End session when user logs out
if (userLoggedOut) {
  await instance.destroy();
}
```

:::note
After calling `destroy()`, you can reinitialize the web channel with `MoveoAI.init()`.
:::

### Styling

#### setCSSVariables()

Dynamically customize the web channel appearance at runtime using CSS variables. This enables per-customer theming without code changes.

```javascript
instance.setCSSVariables({
  "--moveo-header-text-color": "#10038C",
  "--color-options-background": "#CCF3FD",
  "--color-options-foreground": "#10038C",
});
```

**Available CSS variables:**

| Variable | Purpose |
|----------|---------|
| `--color-launcher-background` | Launcher button background |
| `--color-launcher-foreground` | Launcher button icon color |
| `--color-opening-message-background` | Teaser message background |
| `--color-opening-message-foreground` | Teaser message text color |
| `--color-options-background` | Quick reply button background |
| `--color-options-foreground` | Quick reply button text |
| `--color-options-border` | Quick reply button border |
| `--color-swimmlane-background` | System message background |
| `--color-swimmlane-foreground` | System message text |
| `--color-carousel-card-background` | Carousel card background |
| `--color-carousel-card-foreground` | Carousel card text |
| `--color-carousel-card-border` | Carousel card border |
| `--color-chat-background` | Chat container background |
| `--moveo-header-background` | Header background color |
| `--moveo-header-text-color` | Header text and icon color |
| `--font-size-brain-message` | AI message text size (`small`, `medium`, or `large`) |

**Example: Custom branded theme**

```javascript
instance.setCSSVariables({
  "--moveo-header-text-color": "#10038C",
  "--color-options-background": "#CCF3FD",
  "--color-options-foreground": "#10038C",
  "--color-options-border": "#CCF3FD",
  "--color-swimmlane-background": "#F2EBE7",
  "--color-swimmlane-foreground": "#1E222D",
});
```

**Example: Launcher customization**

```javascript
instance.setCSSVariables({
  "--color-launcher-background": "#10b981",
  "--color-launcher-foreground": "#ffffff",
  "--color-opening-message-background": "#10b981",
  "--color-opening-message-foreground": "#ffffff",
});
```

**Example: Header customization**

```javascript
instance.setCSSVariables({
  "--moveo-header-background": "#11366b",
  "--moveo-header-text-color": "#ffffff",
});
```

### Localization

#### setLocale()

Change the web channel language dynamically.

```javascript
instance.setLocale("es"); // Switch to Spanish
```

## Event listeners

Subscribe to web channel events to track user interactions and session changes.

### Session events

#### onSessionCreated

Fired when a new conversation starts.

```javascript
instance.onSessionCreated(() => {
  console.log("New session started");
  // Track in analytics
  analytics.track("Chat Started");

  // Set initial context
  instance.updateContext({
    page_url: window.location.href,
    timestamp: new Date().toISOString(),
  });
});
```

#### onSessionReconnected

Fired when reconnecting to existing session (with history enabled).

```javascript
instance.onSessionReconnected(() => {
  console.log("Reconnected to existing session");
  // Update context with new page info
  instance.updateContext({
    returned_user: true,
    return_page: window.location.pathname,
  });
});
```

#### onSessionClosed

Fired when the chat session terminates.

```javascript
instance.onSessionClosed(() => {
  console.log("Session terminated");
  // Clean up or redirect
  if (shouldRedirect) {
    window.location.href = "/thank-you";
  }
});
```

### Live chat events

#### onConversationClosed

Fired when live chat conversation is resolved/closed.

```javascript
instance.onConversationClosed(() => {
  console.log("Live chat ended");
  // Show feedback form
  showCustomFeedbackModal();
});
```

#### onMemberLeave

Fired when an agent leaves the conversation.

```javascript
instance.onMemberLeave(() => {
  console.log("Agent left the conversation");
  // Notify user
  showNotification("Agent has disconnected");
});
```

### Window events

#### onWebchatOpened

Fired when chat window opens.

```javascript
instance.onWebchatOpened(() => {
  // Pause video when chat opens
  videoPlayer.pause();
  // Track engagement
  analytics.track("Chat Opened");
});
```

#### onWebchatClosed

Fired when chat window closes.

```javascript
instance.onWebchatClosed(() => {
  // Resume video when chat closes
  videoPlayer.play();
  // Save draft message if any
  saveDraftMessage();
});
```

### Activity tracking

#### onUserActivity

Fired on any user activity in the chat.

```javascript
let inactivityTimer;

instance.onUserActivity(() => {
  // Reset inactivity timer
  clearTimeout(inactivityTimer);
  inactivityTimer = setTimeout(() => {
    console.log("User inactive for 5 minutes");
  }, 300000);
});
```

## Analytics events

Track detailed user interactions with analytics events.

### Setup

```javascript
instance.onAnalyticsEvent((eventData) => {
  const { event, properties, timestamp } = eventData;

  // Send to your analytics platform
  analytics.track(event, {
    ...properties,
    chat_session_id: eventData.session_id,
    timestamp: timestamp,
  });
});
```

### Available events

#### Interaction events

- `launcher_clicked` - User clicks launcher
- `chat_expanded` - Chat window opens
- `close_icon_clicked` - Close button clicked
- `message_click` - Message bubble clicked

#### Session events

- `session_start` - New session begins
- `session_end` - Session ends
- `welcome_form_submitted` - Pre-chat form completed

#### Engagement events

- `rating_clicked` - User selects rating
- `rating_submitted` - Rating confirmed
- `download_conversation_clicked` - Export chat

#### Popover events

- `popover_inactivity_end_chat_clicked` - End inactive chat
- `popover_inactivity_continue_clicked` - Continue after inactivity
- `popover_resolved_continue_clicked` - Continue resolved chat

### Event data structure

```javascript
{
  "timestamp": "2025-01-20T10:30:45.123Z",
  "event": "launcher_clicked",
  "session_id": "uuid-here", // Absent before a session exists
  "properties": {} // Event-specific extras
}
```

## Advanced integration patterns

### Custom launcher

Hide default launcher and use custom button:

```javascript
MoveoAI.init({
  integrationId: "YOUR-INTEGRATION-ID",
  version: "v2",
  launcher: { show: false }, // Hide default launcher
}).then((instance) => {
  // Custom button opens chat
  document.getElementById("custom-chat-btn").addEventListener("click", () => {
    instance.openWindow();
  });
});
```

### Contextual messaging

Send different messages based on page:

```javascript
const pageMessages = {
  "/products": "Looking for product information?",
  "/pricing": "Need help choosing a plan?",
  "/support": "How can we assist you today?",
};

instance.sendMessage({
  text: pageMessages[window.location.pathname] || "Hello!",
});
```

### User authentication flow

```javascript
// After user logs in
async function onUserLogin(user) {
  // Destroy old session
  if (window.chatInstance) {
    await window.chatInstance.destroy();
  }

  // Initialize authenticated session
  window.chatInstance = await MoveoAI.init({
    integrationId: "YOUR-INTEGRATION-ID",
    identityToken: () => fetchUserToken(user.id),
    version: "v2",
  });

  // Set user context
  window.chatInstance.updateContext({
    user: {
      display_name: user.name,
      email: user.email,
    },
  });
}

// After user logs out
async function onUserLogout() {
  await window.chatInstance?.destroy();
  window.chatInstance = undefined;
}
```

`fetchUserToken` returns a promise with a JWT from your server. To learn when the web channel calls
it, see [Keep the token fresh](https://docs.moveo.ai/docs/integrations/web/web-getting-started.md#keep-the-token-fresh).

### Analytics integration

```javascript
// Google Analytics 4
instance.onAnalyticsEvent((eventData) => {
  gtag("event", eventData.event, {
    chat_session_id: eventData.session_id,
    engagement_time_msec: 100,
  });
});

// Segment
instance.onAnalyticsEvent((eventData) => {
  analytics.track(eventData.event, eventData.properties);
});

// Mixpanel
instance.onAnalyticsEvent((eventData) => {
  mixpanel.track(eventData.event, eventData.properties);
});
```

### Error handling

```javascript
MoveoAI.init({
  integrationId: "YOUR-INTEGRATION-ID",
  version: "v2",
})
  .then((instance) => {
    window.chatInstance = instance;
  })
  .catch((error) => {
    console.error("Chat initialization failed:", error);

    // Show fallback contact options
    document.getElementById("fallback-contact").style.display = "block";

    // Report to monitoring
    errorReporting.log(error);
  });
```

### Multi-language support

```javascript
// Detect user language preference
const userLang =
  localStorage.getItem("language") || navigator.language.substring(0, 2);

// Initialize with user's language
MoveoAI.init({
  integrationId: "YOUR-INTEGRATION-ID",
  language: userLang,
  version: "v2",
}).then((instance) => {
  // Allow language switching
  document.getElementById("lang-selector").addEventListener("change", (e) => {
    instance.setLocale(e.target.value);
    localStorage.setItem("language", e.target.value);
  });
});
```

## Testing and debugging

### Development mode

```javascript
const isDev = window.location.hostname === "localhost";

MoveoAI.init({
  integrationId: isDev ? "DEV-INTEGRATION-ID" : "PROD-INTEGRATION-ID",
  version: "v2",
}).then((instance) => {
  if (isDev) {
    // Expose instance for debugging
    window.debugChat = instance;

    // Log all events
    instance.onAnalyticsEvent(console.log);
  }
});
```

### Event monitoring

```javascript
// Monitor all chat events
const events = [
  "onSessionCreated",
  "onSessionReconnected",
  "onSessionClosed",
  "onWebchatOpened",
  "onWebchatClosed",
];

events.forEach((eventName) => {
  instance[eventName](() => {
    console.log(`Event fired: ${eventName}`, new Date());
  });
});
```

## Performance optimization

### Lazy loading

```javascript
// Load chat only when needed
function loadChat() {
  const script = document.createElement("script");
  script.src = "https://web.moveo.ai/web-client.min.js";
  script.onload = () => {
    MoveoAI.init({
      integrationId: "YOUR-INTEGRATION-ID",
      version: "v2",
    });
  };
  document.body.appendChild(script);
}

// Load on user interaction
document
  .getElementById("chat-trigger")
  .addEventListener("click", loadChat, { once: true });
```

### Resource cleanup

```javascript
// Clean up on page unload
window.addEventListener("beforeunload", () => {
  if (window.chatInstance) {
    // Save conversation state if needed
    localStorage.setItem(
      "chatState",
      JSON.stringify({
        timestamp: Date.now(),
        page: window.location.href,
      })
    );
  }
});
```

## Security considerations

1. **Never expose sensitive data** in client-side code
2. **Validate tokens** server-side before passing to web channel
3. **Use HTTPS** for all communications
4. **Implement rate limiting** for API calls
5. **Sanitize user input** before passing to context
6. **Monitor for abuse** using analytics events

## Next steps

- [Platform-specific integration guides](https://docs.moveo.ai/docs/integrations/web/web-troubleshooting.md)
- [Configuration options](https://docs.moveo.ai/docs/integrations/web/web-configuration.md)
