> ## Documentation Index
> Fetch the complete documentation index at: https://docs.botbrains.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Web SDK

> Control the website chat widget programmatically with JavaScript

<Note>
  If you would like to see any of the Roadmap features, something else or have feedback on the existing API, reach out to [liam@botbrains.io](mailto:liam@botbrains.io).
</Note>

The Web SDK allows you to control the launcher bubble from the global JavaScript object `$botbrains`.

The SDK ships by default and we will expand the API based on user needs. See Roadmap.

<img src="https://mintcdn.com/botbrains/iwe7EG2H5FvzvT9J/images/web-sdk/launcher-bubble.png?fit=max&auto=format&n=iwe7EG2H5FvzvT9J&q=85&s=7872e6d64d2d95dbed9802ddfd3290d0" alt="Chat launcher bubble in the bottom-right corner of a website" data-generation-prompt="Take a screenshot of the botBrains chat widget launcher visible on a website page. Show the launcher bubble in its default position (bottom-right corner). Use a real website or demo page with the widget embedded. Viewport: 1920x1080. Collapse the platform sidebar if visible. Capture just the website/widget area, not the platform UI." width="500" height="400" data-path="images/web-sdk/launcher-bubble.png" />

## Prerequisite

<Warning>
  The SDK is **NOT** supported if you use the deprecated iFrame integration. Use the launcher and benefit from all new features.
</Warning>

The SDK will assume you run the code via the launcher integration.

```html theme={null}
<script type="text/javascript">
  $botbrains = [];
  $botbrains.push(["set", "config", {
      frameId: 'YOUR_FRAME_ID',
  }]);
  (function(){d = document;s = d.createElement('script');s.src = 'https://chat.botbrains.io/loader.js';s.type = 'module';s.async = 1;d.getElementsByTagName('head')[0].appendChild(s);})();
</script>
```

## Use Cases

### Hide Launcher on specific pages

```javascript theme={null}
// Check if the current page matches a specific URL
if (window.location.pathname === "/specific-page") {
  $botbrains.push(["do", "chat.hide"]);
}
```

### Hide Launcher on small devices

```javascript theme={null}
// Check the screen width and hide the launcher if the width is below a threshold (e.g., 600px)
if (window.innerWidth < 600) {
  $botbrains.push(["do", "chat.hide"]);
}
```

### Integrated Product Help - Buttons

```html theme={null}
<button
  onclick="$botbrains.push(['do', 'message.send', 'How does Feature XY work?'])"
>
  Get Help
</button>
```

### Annotate User Data

```javascript theme={null}
const data = {
	first_name: "Liam",
	last_name: "van der Viven",
	email: "liam@botbrains.io",
	phone: "+4915168433056",
	external_attributes: {
		"plan": "business",
	}
};
$botbrains.push(["set", "user.data", data]);
```

### Identify Users

We also support **identifying users** against our system. Please talk to [liam@botbrains.io](mailto:liam@botbrains.io) for get an introduction.

### Change the suggestions

```javascript theme={null}
if (window.location.pathname === "/product-abc")
	$botbrains.push(["set", "chat.suggestions", ["What ROI did customers see with ABC?", "Does ABC have regional hosting?", "Can I get a demo of ABC?"]])
```

## Docs

You can then use the `$botbrains` object via `.push` immediately below adding our script.

`.push` allows you to call `.do` `.set` `.on` and `.off` without errors.

If you need `.is` or `.on`, store a callback in `window.BOTBRAINS_ON_LOADED`.

* `.is` to branch your code based on our state
* `.do` to trigger actions, don't return values
* `.set` to modify state, annotate users and more
* `.on` and `.off` for registering/unregistering callbacks
* `.get` returns a Promise

On a page that has botBrains loaded, you can open the Developer Console and use `$botbrains.help()` to see all command names.

## Commands

do-Commands are by default async and don't return anything. This allows you to call them at any point, even before the SDK is ready.

```javascript theme={null}
// Handle Visibility of complete system
$botbrains.push(["do", "chat.show"]);
$botbrains.push(["do", "chat.hide"]);

// Expand Chat
$botbrains.push(["do", "chat.open"]);
$botbrains.push(["do", "chat.close"]);
$botbrains.push(["do", "chat.toggle"]);

// Change Position
$botbrains.push(["set", "chat.side", "left"]); // or 'right'
$botbrains.push(["set", "chat.marginSide", "20px"]); // or '10rem' or '10vw' or ...
$botbrains.push(["set", "chat.marginBottom", "20px"]); // ...

// Only if Previews are enabled, you can manually control them
$botbrains.push(["set", "preview.show"])
$botbrains.push(["set", "preview.hide"])

// Setting custom message tags
$botbrains.push(["set", "message.tags", [["Name", "Value"]]]);

// Prefill the message box
$botbrains.push(["set", "message.text", "Hi, how does product XY work?"]);

// Send the current message box
$botbrains.push(["do", "message.send"]);

// Combined: Prefill and send question immediately
$botbrains.push(["do", "message.send", "Hi, how does product XY work?"]);
```

<img src="https://mintcdn.com/botbrains/iwe7EG2H5FvzvT9J/images/web-sdk/chat-expanded.png?fit=max&auto=format&n=iwe7EG2H5FvzvT9J&q=85&s=b439590ccbb75e9b9836c73f7810a9b9" alt="Expanded chat widget showing conversation messages and input box" data-generation-prompt="Take a screenshot of the botBrains chat widget in expanded/open state on a website. Show the full chat panel with conversation history visible (use sample or real messages), the message input field, and the launcher bubble. Position should be on the right side of the screen. Viewport: 1920x1080. Collapse the platform sidebar if visible. Capture the website/widget area only." width="420" height="740" data-path="images/web-sdk/chat-expanded.png" />

## Conditionals

```javascript theme={null}
// Check if the other commands are available
$botbrains.is("chat.ready");
$botbrains.is("chat.visible");
$botbrains.is("chat.opened");

$botbrains.is("preview.visible");
```

### Personalization - Theme and Localization

By default, we will automatch user preferences and choose the most fitting value. You can manually control them.

```javascript theme={null}
// Theme - defaults to user preference; values are "light"|"dark"|"auto"
$botbrains.push(["set", "config.theme", "dark"]);

// Locale - defaults to user preference; Values must be in BCP 47 'de' or 'de-CH'
$botbrains.push(["set", "config.locale", "de-CH"]);
```

## Events

```javascript theme={null}
// You can register and unregister functions with the same identity to run on a event.
// Callbacks take a single payload argument.
$botbrains.push(["on", event, callback]);
$botbrains.push(["off", event, callback]);

// Example
$botbrains.push(["on", "config.loaded", (config) => console.log(config)]);
```

Currently supported events are:

* `chat.ready`
* `frame.loaded`
* `chat.opened`
* `chat.closed`
* `message.sent`

### message.sent

Fires whenever the user sends a message. Use it to track conversations in your own analytics or trigger actions on your page.

```javascript theme={null}
$botbrains.push(["on", "message.sent", (event) => {
  console.log("User sent:", event.text);
  console.log("Conversation ID:", event.conversationId);
}]);
```

| Field            | Type             | Description                               |
| ---------------- | ---------------- | ----------------------------------------- |
| `text`           | `string`         | The message the user typed or selected    |
| `conversationId` | `string \| null` | Current conversation ID, or `null` if new |
| `attachments`    | `FileData[]`     | Any attached files                        |
| `isSuggestion`   | `boolean`        | Whether the user clicked a suggestion     |

## Users

### Data

You can annotate user data and additional arbitrary JSON under `external_attributes` up to 8 KB.

```javascript theme={null}
$botbrains.push(["set", "user.data", {
	first_name: "Liam",
	last_name: "van der Viven",
	email: "liam@botbrains.io",
	phone: "+4915168433056",
	external_attributes: {
		plan: "business",
		joined_on: "2024-04-09"
	}
}]);
```

### Identify

You can also identify users, which enables **cross device session** continuity by setting an `external_id`. Be careful, you may only set `external_id` once. Two users with the same `external_id` will be able to read messages of the other user. Please check your implementation by reading our **[Complete Guide to Users](/concepts/users)** or talking to [ben@botbrains.io](mailto:ben@botbrains.io).

```javascript theme={null}
$botbrains.push(["do", "user.identify", ["user_58066af9-eae5-4315-99e7-967993f43c07", {
	first_name: "Liam",
	// ... properties that are also supported by user.data
}]]);
```

## Debugging

If you have issues, enable verbose logs with `window.BOTBRAINS_DEBUG = true` or `?botbrainsDebug=true` in the URL.

## Roadmap

There are many ways we could expand the API to control more parts of the Chat.

* [ ] Support Attachments
  ```
  set message.file ["Myfile.pdf", "application/pdf", "Some text content or an ArrayBuffer from FileReader().result"]
  ```

Missing something? Let us know what you would like to see, [support@botbrains.io](mailto:support@botbrains.io).

## Frequently Asked Questions

Coming soon.
