# Widget JavaScript API

ConnectiveOne widget provides a JavaScript API for controlling widget behavior from your website. This allows programmatically opening/closing chat, changing parameters, passing events to the scenario, and integrating the widget with SPA applications.

## Main Functions

### Widget Initialization

**`kw('init', {...})`** — initializes the widget with parameters.

**Parameters:**
- `bot_id` — bot identifier (default 1)
- `user_id` — user identifier (optional, generated automatically)
- `language_code` — interface language (uk, ru, en, etc.)
- `params_from_site` — additional parameters for the scenario
- `colors` — widget color scheme
- `open_on_msg` — automatically open chat when receiving a message
- `recognize_user_meta` — collect client data for the operator panel and Statistics: **enabled by default** (`true`). Adds IP address, user agent, auto-detected launch platform (`source_platform`), and embedding page hostname (`source_hostname`). Set to `false` to disable
- `move_to_body` — optional stability flag for floating widget mode. Default: `false`. When set to `true`, the widget moves its rendered root to `document.body` and removes duplicate empty `#kwizbot_widget` placeholders created by the host page. Do not use it for `inline` or `frame` placement

**Example:**
```javascript
kw('init', {
  bot_id: 1,
  language_code: "uk",
  params_from_site: {
    utm_source: "widget",
    company_name: "TV123"
  }
});
```

### Chat Control

**`kw_event('openchat', 1)`** — open chat

**`kw_event('openchat', 0)`** — close chat

**Example:**
```javascript
// Open chat on button click
document.getElementById('open-chat-btn').addEventListener('click', function() {
  kw_event('openchat', 1);
});
```

### Changing Title and Subtitle

**`kw_event('command', { title: '...', subtitle: '...' })`** — change chat title and subtitle

**Example:**
```javascript
kw_event('command', {
  title: "New Title",
  subtitle: "New Subtitle"
});
```

### Navigate to Scenario Entry Point

**`kw_event('emitevent', { event: 'alias', alias: 'test-alias' })`** — navigate to the specified alias in the scenario

**Example:**
```javascript
kw_event('emitevent', {
  event: 'alias',
  alias: 'product-inquiry'
});
```

### Pass Parameters from Website

**`kw_event('kwsetparamsfromsite', { params_from_site: {...} })`** — change parameters during operation

**Example:**
```javascript
kw_event('kwsetparamsfromsite', {
  params_from_site: {
    company_name: 'TV123123',
    page_url: window.location.href
  }
});
```

### Change Colors

**`kw_event('kwcolor', { header: { bg: '#FF0000' } })`** — change widget colors

**Example:**
```javascript
kw_event('kwcolor', {
  header: {
    bg: "linear-gradient(130deg, #734FE1, #D14EE0)",
    text: "#ffffff"
  }
});
```

### Working with SPA

**`kw_event('kwreinitwidget', {...})`** — reinitialize widget (for SPA)

**Parameters:**
- `user_id` — change user (or `null` for new chat)
- `params_from_site` — update parameters
- `title`, `subtitle` — change title

**Example:**
```javascript
// Create new chat
kw_event('kwreinitwidget', { user_id: null });

// Change parameters
kw_event('kwreinitwidget', {
  params_from_site: { type: 'mobile' }
});
```

**`kw_event('kwvisiblelauncher', { visible: false })`** — hide/show launcher

**Example:**
```javascript
// Hide launcher
kw_event('kwvisiblelauncher', { visible: false });

// Show launcher
kw_event('kwvisiblelauncher', { visible: true });
```

### Save State

**`kw_event('widgetstatus', 1)`** — save chat state in localStorage

After execution, the following is saved in `localStorage`:
- `isChatOpen` — widget state (collapsed/expanded)
- `connectState` — operator connection state

## Widget Events

You can listen to widget events:

**`widgetChatOpened`** — chat opened

**`widgetChatClosed`** — chat closed

**Example:**
```javascript
document.addEventListener("widgetChatOpened", function(event) {
  console.log('Chat opened', event);
  // Your handling code
});

document.addEventListener("widgetChatClosed", function(event) {
  console.log('Chat closed', event);
  // Your handling code
});
```

## Custom Code

You can add custom JavaScript code that executes before widget initialization. The code has access to:

- `embed_state` — widget state before initialization
- `kw_event()` — function to call events
- `kw_event_trigger()` — function to trigger events

**Where to configure:** Settings → Bots → select bot → Widget → Custom Code

**Custom Code Example:**
```javascript
// Modify parameters before initialization
embed_state.params_from_site = {
  ...embed_state.params_from_site,
  page_url: window.location.href,
  user_agent: navigator.userAgent
};

// Integration with Google Analytics
if (window.gtag) {
  window.addEventListener('widgetChatOpened', function() {
    window.gtag('event', 'chat_opened');
  });
}
```

## Limitations

- Only one widget instance can be on one page
- Widget works only through HTTPS (except localhost)
- Domains for widget must be added to CORS settings
- Spam protection: automatic blocking at 10+ messages in 5 seconds

## Related Articles

- [What is a widget](/en/channels/explanation/what-is-widget.md)
- [Connect widget to website](/en/channels/how-to/setup-widget-on-website.md)
- [Pass parameters from website to scenario](/en/channels/how-to/pass-parameters-from-widget.md)
- [Manage widget from website](/en/channels/how-to/manage-widget-from-site.md)
- [Work with SPA applications](/en/channels/how-to/work-with-widget-spa.md)
- [Use Custom Code](/en/channels/how-to/use-widget-custom-code.md)
- [Data exchange with widget](/en/integrations/explanation/what-are-integrations.md#widget-data-exchange)

