> For the complete documentation index, see [llms.txt](https://support.mailagent.email/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://support.mailagent.email/widget/javascript-api.md).

# JavaScript API

The widget exposes a global `window.MailAgent` object with methods to open, control, and close the widget programmatically.

## `MailAgent.open(options)`

Opens the widget and returns a handle for interacting with it.

```javascript
const widget = await MailAgent.open({
  bottom: "20px",
  right: "20px",
  width: "400px",
  height: "600px"
});
```

**Returns:** `Promise<WidgetHandle>`

See [Configuration](/widget/configuration.md) for all available options.

## Widget Handle

The object returned by `MailAgent.open()` provides the following interface:

### `widget.send(message)`

Send a message to the chat programmatically. This triggers the AI assistant to respond as if the user typed the message.

```javascript
// Send a text message
widget.send({ text: "Draft a follow-up email to the client" });
```

```javascript
// Send with file attachments
widget.send({
  text: "Summarize this document",
  files: [file]
});
```

### `widget.mounted`

A read-only boolean indicating whether the widget iframe is still attached to the DOM.

```javascript
if (widget.mounted) {
  widget.send({ text: "Hello!" });
}
```

### `widget.unmount()`

Closes and removes the widget from the page with a fade-out animation.

```javascript
widget.unmount();
```

## Full Example

```html
<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
</head>
<body>
  <button id="open-chat">Open Chat</button>
  <button id="close-chat" disabled>Close Chat</button>
  <button id="send-msg" disabled>Ask about pricing</button>

  <script
    src="https://widget.mailagent.email/connect/connect.js"
    data-user-id="YOUR_USER_ID"
    data-suggestions='[{"icon":"💬","text":"Help me write an email"}]'
  ></script>

  <script>
    let widget = null;

    document.getElementById('open-chat').addEventListener('click', async () => {
      widget = await MailAgent.open({
        bottom: '20px',
        right: '20px',
        width: '400px',
        height: '600px',
      });

      document.getElementById('close-chat').disabled = false;
      document.getElementById('send-msg').disabled = false;
    });

    document.getElementById('close-chat').addEventListener('click', () => {
      widget?.unmount();
      widget = null;
      document.getElementById('close-chat').disabled = true;
      document.getElementById('send-msg').disabled = true;
    });

    document.getElementById('send-msg').addEventListener('click', () => {
      widget?.send({ text: 'What are your pricing plans?' });
    });
  </script>
</body>
</html>
```

## Events

The widget communicates with the parent page via `postMessage`. You can listen for these events if you need deeper integration:

| Event Type          | Direction       | Description                            |
| ------------------- | --------------- | -------------------------------------- |
| `init`              | Parent ← Widget | Widget requests initialization data.   |
| `init`              | Parent → Widget | Parent sends config (userId, etc.).    |
| `initialized`       | Parent ← Widget | Widget is fully loaded and ready.      |
| `__widget_resize__` | Parent ← Widget | Widget reports its content dimensions. |
| `close`             | Parent ← Widget | Widget requests to be closed.          |
| `send`              | Parent → Widget | Parent sends a message to the chat.    |

> **Note:** You typically don't need to handle these events directly — the `MailAgent.open()` API manages them for you. These are documented for advanced use cases only.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://support.mailagent.email/widget/javascript-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
