Widget JavaScript API
Control the widget from your page with window.SiteTrellis: open, close, toggle, identify visitors, set attributes, and listen to events.
Last updated:
When the widget script loads it defines a single global function, window.SiteTrellis. Use it to open the chat from your own buttons, tell the agent who the visitor is, pass context about the page or session, and react to what happens in the chat. Everything here is optional: the widget works with no code at all.
Calling the API#
The signature is always SiteTrellis(command, argument1, argument2):
SiteTrellis('open');
SiteTrellis('identify', { name: 'Priya Shah', email: '[email protected]', id: 'u_1042' });
SiteTrellis('on', 'message', function (m) { console.log(m.role, m.content); });
Before the script has loaded#
The widget script loads with async, so your own code may run first. The widget supports a standard command queue: define a small stub before the script tag and any calls made early are replayed in order once the widget starts.
<script>
window.SiteTrellis = window.SiteTrellis || function () {
(window.SiteTrellis.q = window.SiteTrellis.q || []).push(arguments);
};
SiteTrellis('identify', { name: 'Priya Shah', email: '[email protected]' });
</script>
<script src="https://cdn.sitetrellis.com/v/a44108d9c4521120/widget.js" data-site="site_xxxxxxxxxxxxxxxx" async></script>
Without the stub, window.SiteTrellis does not exist until the script has run, and calling it throws an error. If you cannot add the stub, wait for the script's load event instead:
function whenSiteTrellisReady(fn) {
if (typeof window.SiteTrellis === 'function') return fn();
var s = document.querySelector('script[data-site]');
if (s) s.addEventListener('load', fn);
}
whenSiteTrellisReady(function () { SiteTrellis('identify', { email: '[email protected]' }); });
Commands#
| Command | Argument | What it does |
|---|---|---|
open | none | Opens the chat window (unless the current page is excluded by the site's page rules). |
close | none | Closes the chat window. The conversation continues in the background. |
toggle | none | Opens it if closed, closes it if open. |
expand | none | Switches to the large view (a roomy centred panel, or full screen on phones) and opens the chat if it is closed. Does nothing when the site has turned the expand button off, or on a phone where the chat is already full screen. See Themes and the expanded view. |
collapse | none | Returns to the small window. The chat stays open. |
toggleExpand | none | Expands if it is small, collapses if it is large. |
identify | object, optional token | Tells the agent who the visitor is. Same as setAttributes, and additionally maps an id property to the attribute user_id. Without a token the details are self-reported. Pass a token signed by your server as the second argument (or alone, identify('token')) to make them verified: see Signed identity. |
setAttributes | object | Adds or updates attributes about the visitor or session (for example a plan or the product being viewed). |
sendMessage | string | Opens the chat and sends the text as the visitor's message. Use for "Ask about this product" buttons. Called before the widget is ready, it waits; if the site requires consent, it waits until the visitor has accepted; if the previous chat ended, it starts a new one. The normal rate limits apply. |
event | name, object | Fires a page event. If the site has a rule for that name (Appearance, Page events) the widget runs it: open the chat, show a text bubble, set attributes. See Auto-open, exit intent and consent. |
reset | none | Forgets the visitor: drops the stored conversation, attributes and verified identity and shows the greeting again. Call it when your user logs out. |
on | event name, callback | Subscribes to a widget event (see below). |
off | event name, callback | Removes a callback you added with on. Pass the same function. |
newChat | none | Ends the current conversation and starts a fresh one. |
destroy | none | Removes the widget from the page. After this, SiteTrellis(...) calls are queued and do nothing. |
Unknown commands log a warning in the console.
Identifying visitors and passing attributes#
Attributes are simple name and value pairs. They are sent to SiteTrellis, stored with the visitor and conversation, shown to your team in the inbox, available to the prompt as {{visitor.KEY}} variables (see Build your agent), and included in lead and handoff data.
SiteTrellis('identify', {
id: 'u_1042', // stored as user_id
name: 'Priya Shah', // {{visitor.name}}
email: '[email protected]',
plan: 'pro', // {{visitor.plan}}
company: 'Northwind'
});
// Later, e.g. when the visitor browses a product:
SiteTrellis('setAttributes', { product: 'Trail Shoe 2', cart_value: 129 });
- Names must start with a letter and contain only letters, digits, underscore, dot or hyphen, up to 40 characters. Values must be strings, numbers or booleans (objects and arrays are ignored). Values are shortened to 500 characters and up to about 30 attributes are accepted in a call.
- An
emailthat is not a valid address is dropped. - Calls made before the chat session exists are remembered and sent when the chat starts; later calls are sent shortly after (updates within a fraction of a second are merged).
- The widget automatically sends the page address and page title when the chat starts, so you do not need to pass them yourself. They are available as
{{page.url}}and{{page.title}}.
identify data to grant access or reveal private information. If the agent has a tool that returns account data, either authenticate that on your server (for example with a session cookie or signed link) or use a signed identity: values inside a token signed by your server are verified and available to tools as {{verified.user_id}}, whereas email and the other values passed in the browser stay untrusted.Also avoid sending anything sensitive, such as passwords or card numbers: attributes can be included in the text sent to your AI provider.
Events#
Subscribe with SiteTrellis('on', eventName, callback). The callback receives one argument, shown below. An error in your callback is caught and does not affect the widget.
| Event | Callback argument | When |
|---|---|---|
ready | { site } | The widget has loaded its configuration and drawn the launcher. It does not fire if the widget is unavailable (no published agent, or origin not allowed). |
open | none | The chat window opened. |
close | none | The chat window closed. |
expand | none | The chat switched to the large view, with the header button or the API. |
collapse | none | The chat returned to the small window. |
message | { role, content, id } | A new reply arrived from the AI or an operator (role is assistant or operator). |
message:sent | { content, id } | The visitor's message was accepted by the server. |
unread | number | The count of unread replies changed while the window was closed or the tab hidden. |
conversation:started | { id, resumed } | A conversation was started, or an earlier one was resumed (resumed is true). |
conversation:ended | { id } | The conversation ended. |
form:submitted | { form } | The visitor submitted a form; form is prechat, lead or escalation. |
identity | { verified, user_id?, reason? } | The result of a signed identity token: verified, or the reason it was not accepted (the chat keeps working either way). |
event | { name, data } | A valid page event was fired with SiteTrellis('event', ...), whether or not a rule exists for it. |
reset | none | The visitor was reset. |
error | { code } | A message could not be sent. code follows the API error codes (or network). |
Event payloads are for your page's own use (analytics, UI). Conversation contents are only available to your callbacks in the visitor's own browser; they are not otherwise sent to third parties by the widget.
Examples#
Open the chat from your own button#
<button type="button" onclick="SiteTrellis('open')">Chat with us</button>
<button type="button" onclick="SiteTrellis('sendMessage', 'Is this available in size 42?')">Ask about this product</button>
Send chat events to your analytics#
window.dataLayer = window.dataLayer || [];
SiteTrellis('on', 'conversation:started', function (c) {
dataLayer.push({ event: 'chat_started', chat_resumed: c.resumed });
});
SiteTrellis('on', 'form:submitted', function (f) {
if (f.form === 'lead') dataLayer.push({ event: 'chat_lead_submitted' });
});
Single-page apps#
The widget watches for address changes made by your router and re-checks the site's page rules, so include and exclude patterns keep working as visitors navigate. Update attributes as the visitor moves around:
// e.g. in a React router effect
SiteTrellis('setAttributes', { screen: location.pathname });
// On logout: forget the visitor so the next person on a shared device starts fresh
SiteTrellis('reset');
Local testing with data-api#
By default the widget derives its API address from the script address: cdn.example.com becomes api.example.com. If you run SiteTrellis yourself or are testing against a development environment, or if you serve widget.js from a different host, add a data-api attribute with the API origin (no path):
<script src="https://cdn.sitetrellis.com/v/a44108d9c4521120/widget.js" data-site="site_0123456789abcdef"
data-api="https://api.sitetrellis.com" async></script>
Remember that the page you test from must be in the site's allowed origins (for example http://localhost:3000), or the API refuses it.
Behavior notes#
- The widget remembers an open window and the conversation across page loads when persist session is on (see Widget customization).
- If your page contains the embed snippet twice, the second copy does nothing; the first one wins.
- Calls made after
destroyare queued but never run. Reload the page to restore the widget. - The JavaScript API is a convenience, not a security boundary. All rules are enforced on the server.