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

# Methods

> Complete reference for every method on window.homieBot, with parameters, return types, and examples.

All methods live on `window.homieBot`, which becomes available after the `homiebot:api-ready` event. Methods that interact with the conversation (`sendMessage`, `getHistory`, `resetChat`, `sendCustomPdpQuestion`) require the iframe to be ready — they wait internally, but you can check readiness with `isReady()` or listen for `homiebot:assistant-ready`.

> [!NOTE]
>
> Always guard against `window.homieBot` being undefined at page load. See
> [Examples](https://docs.yourhomie.ai/en/api-reference/client/examples.md) for a wait-for-ready pattern.

## open()

Opens the chat widget if it is currently closed. Returns `void`.

```js theme={null}
window.homieBot.open();
```

## close()

Closes the chat widget if it is currently open. Returns `void`.

```js theme={null}
window.homieBot.close();
```

## mountEmbeddedChat(options?)

Shows the embedded chat in `#homie-embedded-chat` and hides the floating widget. Use this in single-page shops when opening the assistant page without a full reload. While the embedded chat is mounted, no widget appears, even if you call `open()` or `toggle()`. Returns `void`.

Call the method after the assistant page has rendered an empty container with the fixed, non-configurable ID `homie-embedded-chat`. Set its height yourself; the chat fills the container. Leave the container empty: content inside it is not shown while the chat is mounted. Like all other methods, `mountEmbeddedChat` is available once the API is ready, so wait for the `homiebot:api-ready` event (or check that `window.homieBot` exists). You do not need to wait for `isReady()`.

```js theme={null}
window.homieBot.mountEmbeddedChat({
    title: 'Questions about this product?',
    contextUrl: '/products/rain-jacket-123',
});
```

**`options` (optional)** — omit it or pass `{}` to use the defaults.

| Field | Type | Description |
| - | - | - |
| `title` | string | Optional plain-text heading above the conversation. Leading and trailing whitespace is removed. If omitted or blank, a greeting in the chat language is shown (e.g. “Hello”). |
| `contextUrl` | string | Optional page to use as context, such as the product page the shopper came from. Relative URLs resolve against the current page. If omitted or blank, the browser's referring page is used only if it is a different page with the same protocol, hostname, and port. Otherwise, the assistant page provides the context. |

In a single-page shop, pass the previous product URL explicitly: the browser's referring page does not update on navigation without a reload. Calling `mountEmbeddedChat()` again replaces the embedded chat with the new options.

> [!WARNING]
>
> If the container is missing, the browser console shows a warning and the call has no effect. An existing widget
> remains unchanged. Keep the container empty before mounting and give it an explicit height.

## unmountEmbeddedChat()

Removes the embedded chat and restores the widget according to your existing widget settings. Call it when leaving the assistant page, after the URL has changed to the destination page. Removing the container alone does not restore the widget. Takes no parameters and returns `void`. If no embedded chat is mounted, the call has no effect.

```js theme={null}
window.homieBot.unmountEmbeddedChat();
```

### Example: component lifecycle in a single-page shop

Load the embed script once for your shop and leave `window.homieBotConfig.embeddedChat` unset. This Svelte example mounts the chat after the page component renders and removes it when the component is destroyed. Your router supplies `contextUrl` with the product URL saved before navigating to the assistant page and updates the destination URL before destroying the component.

```svelte AssistantPage.svelte theme={null}
<script>
    import { onMount } from 'svelte';

    let { contextUrl } = $props();

    onMount(() => {
        const mountChat = () => {
            window.homieBot.mountEmbeddedChat({
                title: 'Questions about this product?',
                contextUrl,
            });
        };

        if (window.homieBot) {
            mountChat();
        } else {
            window.addEventListener('homiebot:api-ready', mountChat, { once: true });
        }

        return () => {
            window.removeEventListener('homiebot:api-ready', mountChat);
            window.homieBot?.unmountEmbeddedChat();
        };
    });
</script>

<div id="homie-embedded-chat" style="height: calc(100dvh - 64px);"></div>
```

For installation and a product-page-to-assistant example, see [Embedded Chat](https://docs.yourhomie.ai/en/user-guide/installation/embedded-chat.md).

## resetChat()

Clears the current conversation and its locally stored history. Returns a `Promise<void>` that resolves after the iframe confirms the reset. It rejects if the iframe cannot become ready or if the confirmation does not arrive within five seconds.

```js theme={null}
await window.homieBot.resetChat();
```

## toggle()

Toggles the widget between open and closed. Returns `void`.

```js theme={null}
window.homieBot.toggle();
```

## isOpen()

Returns `boolean` — whether the widget is currently open. Does not change the UI.

```js theme={null}
if (window.homieBot.isOpen()) {
    console.log('Chat is open');
}
```

## isReady()

Returns `boolean` — whether the chat iframe is fully loaded and ready to accept `sendMessage` and `getHistory`. Use this before sending messages from late-bound code.

```js theme={null}
if (window.homieBot.isReady()) {
    window.homieBot.sendMessage({ text: 'Hello' });
}
```

## sendMessage(input, options?)

Injects a message directly into the chat — ideal for product detail pages (PDPs) or context-driven prompts. Opens the chat first if it is closed. Returns a `Promise`.

```js theme={null}
await window.homieBot.sendMessage(
    { text: 'Do you have this product in grey?' },
    { open: true } // opens the chat before sending
);
```

**`input` (required: `text`)**

| Field | Type | Description |
| - | - | - |
| `text` | string | The message to inject. |
| `id` | string | (optional) Your own reference/tracking ID. |
| `setId` | string | (optional) Question set ID for tracking. |
| `questionId` | string | (optional) Question ID within the set. |
| `newChat` | boolean | (optional) Start a new conversation. |

**`options`**

| Field | Type | Default | Description |
| - | - | - | - |
| `open` | boolean | `true` | Open chat if closed. |
| `maxRetries` | number | `3` | Retries while the iframe initializes. |
| `retryDelay` | number | `300` | Milliseconds between retries. |
| `timeout` | number | `5000` | Total timeout in ms waiting for ACK. |
| `relaxedOrigin` | boolean | `false` | Disable origin checks (special cases only). |

> [!NOTE]
>
> The signature documented above is the supported public contract. The current embed source exposes a simplified
> `sendMessage(input)` form where `input` accepts `text`, `questionSetId`, `questionId`, `type` (`'DEFAULT' |
>       'PDP_QUESTION'`), and `newChat`, and no `options` argument. If you target the latest embed, prefer the `text` /
> `newChat` fields, which are stable across both.

## getHistory()

Returns a `Promise` resolving to the current chat history payload from the iframe. Useful for custom tracking. The request times out after a few seconds if the iframe does not respond.

```js theme={null}
const history = await window.homieBot.getHistory();
console.log('Chat history:', history);
```

## updateMessageMetadata(metadata)

Attaches metadata to the next user message as key-value pairs. Returns `void`. If the iframe is not yet ready, the metadata is queued and sent automatically once the iframe initializes. Multiple calls merge.

```js theme={null}
window.homieBot.updateMessageMetadata({
    productId: '12345',
    category: 'power-tools',
    source: 'pdp',
});
```

**Limits and validation**

| Constraint | Limit |
| - | - |
| Max keys | 5 key-value pairs per call |
| Key length | Max 50 characters |
| Value length | Max 100 characters |
| Key type | Must be a string |
| Value type | String, or `null` to remove a key |

**Merging and removing keys**

* Existing keys can be overwritten with new values.
* Keys are removed by passing `null` as the value.
* Multiple calls are merged — new keys are added, existing keys are updated.

```js theme={null}
// Set initial metadata
window.homieBot.updateMessageMetadata({
    productId: '12345',
    category: 'power-tools',
});

// Update an existing key and add a new one
window.homieBot.updateMessageMetadata({
    category: 'hand-tools', // overwrites existing
    brand: 'Bosch', // adds new key
});

// Remove a key
window.homieBot.updateMessageMetadata({
    brand: null, // removes the key
});
```

> [!WARNING]
>
> **Single-page applications (SPAs):** metadata keys persist across navigation because they live in the global window
> context. When you navigate between pages, clear stale metadata manually by calling `updateMessageMetadata()` with
> `null` values to avoid unintended persistence.

```js theme={null}
// Clear metadata on a route change in an SPA
window.homieBot.updateMessageMetadata({
    productId: null,
    category: null,
    source: null,
});
```

## sendCustomPdpQuestion(questionSetId)

Opens the chat and triggers the custom product-question flow for a given question set. Returns a `Promise`. This method backs the "ask something else" button rendered by the product-questions widget.

```js theme={null}
await window.homieBot.sendCustomPdpQuestion('pdp-questions-set-123');
```

> [!WARNING]
>
> This method is exposed on `window.homieBot` but is primarily intended for the built-in product-questions widget. Use
> it only if you render your own custom product-question entry point.

## initializePdpQuestions()

Loads the product questions for the current URL and renders them into every `#homie-product-questions` element (and every element whose ID starts with `homie-product-questions-`). Returns `Promise<void>`, which resolves once the questions are rendered.

The assistant script renders product questions automatically when the page first loads. If your shop switches pages without a full reload (client-side navigation), call this method after the new page is rendered and its questions element is in the DOM:

```js theme={null}
// After every client-side route change, once the new page is rendered
await window.homieBot?.initializePdpQuestions();
```

* replaces the questions that homie rendered before — calling it repeatedly never duplicates them
* loads the questions for `window.location.href`, so call it after every URL change, once the new URL is set (also when only the query changes)
* removes the previous product's questions as soon as it is called for a new page (another path), so they never show on the wrong product while the new ones load
* when only the query or fragment changed (for example a variant switch), or for the same URL, it keeps the current questions until the new ones replace them, so nothing flickers
* leaves any other content of your own inside the element untouched
* if several calls overlap, only the most recent one is rendered
* if loading fails, the questions already shown for the same page stay
* views are counted at most once per page visit, even if you call it more than once; a query-only change such as a variant switch is the same visit

For a Next.js example, see [Single-page shops](https://docs.yourhomie.ai/en/user-guide/product-questions/setup.md#single-page-shops).

## trackPdpQuestionsView(element, questionSetId)

Reports a qualified view (impression) for self-rendered product questions. Returns `void`. Use this when your shop fetches the product questions from the [REST API](https://docs.yourhomie.ai/en/api-reference/backend/pdp-questions/get-pdp-questions.md) and renders them with its own markup — it applies the same viewability rules as the built-in rendering, so your views and click-through rates stay comparable in the platform's analytics:

* counts only when the element has been at least 50% visible in the viewport for 1 second
* counts at most once per page visit (per product page — query and fragment are ignored, so a variant switch is the same visit)
* safe to call again on framework re-renders — a pending measurement is re-armed on the new element, a counted visit never fires twice

Call it once right after rendering your questions element:

```js theme={null}
// You fetched { questionSetId, questions } from the product questions API
// and rendered your own UI into `container`.
window.homieBot.trackPdpQuestionsView(container, questionSetId);
```

| Parameter | Type | Description |
| - | - | - |
| `element` | Element | The DOM element containing your rendered questions. |
| `questionSetId` | string | The question set ID returned by the questions endpoint. |

> [!NOTE]
>
> Views are the denominator of the click-through rate. If you render questions yourself and never call this method,
> your product pages will show clicks but no views in the analytics.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.