JavaScript API

Methods and events for driving Webchat from your code.

Two surfaces, one runtime:

  • SDK: mount() returns a typed handle. Methods are namespaced: widget.chat.open(), widget.user.identify(...), widget.events.on(...).
  • Script tag: the runtime installs itself on window.Assistify once the loader script runs. Methods are flat: window.Assistify.open(), window.Assistify.identify(...), window.Assistify.reset().

Both surfaces drive the same runtime and emit the same events. They differ in a few places: load() exists only on the SDK; consent is consent.set() and consent.get() on the SDK, setConsent() and getConsent() on window.Assistify; and on the SDK an identify() called right after reset() waits for the new session, while on window.Assistify you wait for ready first. Examples below use the namespaced form; the flat equivalent is shown when it differs.

user.track(), campaigns.show(), consent and the campaign events need @assistifychat/widget 1.2.0 or later on the SDK. The script tag always has them.

Lifecycle

load()

widget.load(): Promise<void>

Inject the loader script if not already injected, and resolve once the runtime fires ready. Idempotent: repeat calls return the same promise. Rejects on script-load failure (network, CSP, adblocker) or after a 30-second timeout, which is also what happens when the boot is refused: a domain missing from Allowed domains, a paused workspace, a blocked visitor. A rejected load() keeps returning the same rejection until destroy().

You rarely need to call this directly. The default behavior of mount() (or the <script> install) loads the runtime immediately. Call load() only when you mounted with autoload: false and want to trigger boot explicitly, for example after a consent banner. See Deferred boot.

reset()

widget.reset(): void

Flat: window.Assistify.reset()

Call this on logout. It wipes the session server-side and locally, then boots again as a fresh anonymous visitor, clearing:

  • The server-side session (DELETE /api/widget/session), with the site events recorded for this browser.
  • The assistify.<widgetId>.vid cookie, plus the localStorage and sessionStorage copies.
  • window.ASSISTIFY_USER if present.
  • Every data-user-* attribute on the <script> element.
  • Unsent message drafts and the persisted UI state.

The consent decision recorded with setConsent() is kept.

Host-registered event listeners survive the reset. The call returns immediately; listen for ready to know the post-reset boot completed.

If the widget has not loaded yet (autoload: false with no boot-triggering call), reset() only clears the visitor's local storage and does not load the widget, so a logout on a deferred page stays free of widget network activity.

destroy()

widget.destroy(): void

Flat: window.Assistify.destroy()

Tears the widget down: it removes the UI, releases listeners, and stops the runtime. Unlike reset() it leaves visitor storage on the host origin intact, which makes it the right call when an SPA route drops the chat; use reset() for logout.

Teardown is reversible within the same page session: calling mount() again, or any boot-triggering method on the handle (load(), chat.open(), chat.close(), chat.toggle(), campaigns.show(), reset()), boots the widget back up and the returning visitor is recognized. Calls made between destroy() and the re-boot are buffered and replayed. Event listeners do not survive destroy(): register them again.

isReady()

widget.isReady(): boolean

true once the widget has booted and acquired a session token.

Chat

chat.open() / chat.close() / chat.toggle()

widget.chat.open();

Flat: window.Assistify.open(), Assistify.close(), Assistify.toggle().

Each emits the corresponding event with source: 'api' when it changes the state: open() on an open panel emits nothing.

User

user.identify(identity)

widget.user.identify({
  email:    '[email protected]',
  userHash: 'HMAC_SHA256_SIGNATURE',
});

Flat: window.Assistify.identify({ email, userHash }).

Every call carries at least one of email, externalId or discordId. userHash is the proof, not the identifier; sending only { userHash }, or only { customAttributes }, is rejected.

  • A signed call attaches the browser to the verified contact its identifiers name, or creates that contact.
  • An unsigned call records the identifiers on the browser's own contact, or on a new one, and never reaches a contact someone else verified. A second unsigned call with other identifiers replaces them on the same contact. To switch between people, see Lifecycle.

The call returns immediately. Listen for identified to learn whether this call was verified (verified: true) and whether it used a contact that already existed instead of creating one (merged: true). Send userHash with every signed call: each call reports its own verdict. See Identity verification.

identify() never sends a verification link. A link is sent when the visitor asks for one in Webchat (the identity form, or Send link on the verification banner) or gives their address to Aiva in the conversation. Reply notifications and rating requests go by email to the address on record, verified or not; to an unverified address they carry no conversation text.

Up to 10 calls an hour are accepted for one email address in your workspace, across every browser. Past that, and on an invalid field, the call is refused and identified reports { verified: false, merged: false }. Call identify() when the identity changes, not on every page.

FieldType
emailstringA valid address, up to 254 characters
externalIdstringYour system's user ID, up to 256 characters
displayNamestringShown to your team as the contact's name, up to 256 characters. Latest identify wins, unless a teammate set the name from the dashboard.
avatarUrlstringContact avatar, an absolute http(s) URL. Latest identify wins.
discordIdstringUp to 64 characters
discordUsernamestring
discordAvatarstringAn absolute http(s) URL
customAttributesRecord<string, JsonValue>Up to 50 keys of up to 128 characters, 16 KB in all. Shallow-merged onto the contact on each identify; shown to your team in the dashboard and usable in campaign targeting.
userHashstringHMAC-SHA256 signature of the identifiers, computed on your server. See Identity verification.

Scalar customAttributes (string, number, boolean) can be targeted by campaigns: in a campaign's Audience, add a condition on the Custom attribute field, type the attribute name (for example plan or cartTotal), choose an operator, and set a value. Numeric operators (>, <, …) coerce both sides to numbers, so cartTotal > 200 works whether you send 200 or "200". Nested objects and arrays are not matchable. Targeting reads the identified contact's attributes, so the visitor must have called identify() first.

user.getVisitorId()

widget.user.getVisitorId(): string | null

Flat: window.Assistify.getVisitorId().

The visitor's anonymous ID (anon_ plus 22 characters; see Visitor recognition), or null when no ID has been minted yet (the runtime mints one on first boot) or storage is unavailable.

user.track(name)

widget.user.track('added_to_cart');

Flat: window.Assistify.track('added_to_cart').

Records that the visitor did something on your website: a site event. A campaign can wait for it on the page (its Behavior), count it as its goal, or reach visitors who did it or never did it (the Site event condition of its Audience). The event is recorded for the visitor's browser, on the page they are on, and follows the visitor to their contact once they are identified.

The call returns immediately and never loads the widget by itself. Up to 60 calls made before the widget has loaded are held and sent once it boots. A held event counts for a campaign waiting for it only on the page it was reported on, so an event reported while the page loads still counts there.

  • Names. 1 to 64 characters: a letter or a digit first, then letters, digits, spaces and _ - . :. A name is matched exactly as written, case included. Use one name per kind of action, such as added_to_cart, signup_started or plan_upgraded, never one per product or per person.
  • No personal data in a name. Anyone reading the page's code can see it, and your team sees it in the visitor's profile: keep emails, names and order numbers out of it.
  • Bounds. One browser records up to 60 events a minute, and the rest of that minute's events are dropped. A workspace keeps up to 200 distinct names; past that a new name is not recorded, while the names already held keep recording. The browser console says when either happens.

The campaign editor offers the names your website has sent, and accepts a name it has not received yet.

Campaigns

campaigns.show(id)

widget.campaigns.show('CAMPAIGN_ID');

Flat: window.Assistify.showCampaign('CAMPAIGN_ID').

Shows one published campaign now. Its id is in the campaign editor: Copy ID in the campaign's menu, or the code shown on a campaign whose Behavior is From code.

The call skips the campaign's audience, pages, timing and behavior, since your code decides who and when. Everything else still applies, and the campaign does not show when one of these holds:

Reason
not_foundNo published campaign with this id runs on this Webchat.
not_runningThe campaign is paused, ended, not started yet, outside its weekly hours, or past the number of campaigns your plan runs at once.
team_offlineThe campaign shows only while the team is online, and nobody is.
unavailableSomething the campaign depends on is unavailable: the teammate who signs it left, or an article it opens is unpublished.
frequencyThe visitor has met the campaign as often as its frequency allows. A visit meets a campaign once.
closed_this_visitThe visitor closed a campaign during this visit.
per_visitThe visit has met as many campaigns as the Webchat allows.
card_on_pageA campaign card already stands on this page.
quietWebchat is open, a conversation is under way, or nothing may be shown to this visitor now.

The call returns immediately: campaign:shown fires when the card appears, and the browser console names the reason when it does not. Called before the widget has loaded, it loads it, as chat.open() does. Without the launcher (launcher: false), a card is not drawn on the page.

A campaign whose Behavior is From code shows only this way: the widget never shows it on its own.

Events

const unsubscribe = widget.events.on('ready', () => { /* ... */ });
unsubscribe();

Flat: window.Assistify.on('ready', cb) and Assistify.off('ready', cb).

EventPayload
ready{ widgetId }Fires once per boot, including after reset().
open{ source: 'api' | 'launcher' | 'campaign' }campaign when a campaign card opened Webchat.
close{ source: 'api' | 'ui' | 'escape' }
identified{ verified, merged }Fires after each identify() call and when the visitor identifies themselves inside the chat. Boot-time identity emits no event. verified: true when the userHash supplied on that call matched your workspace's secret; it reports each call's own verdict, so a broken signing setup shows up immediately. merged: true when the call used a contact that already existed. A call that failed (network, invalid field, rate limit) reports { verified: false, merged: false }.
verified{ verifiedVia: 'HMAC' | 'MAGIC_LINK' | 'OAUTH', merged }Fires when a claimed email is proved: the visitor clicks the sign-in link or the link in a reply email (MAGIC_LINK), or completes Discord sign-in (OAUTH). verifiedVia reports the contact's strongest proof, so it reads HMAC if the contact was already HMAC-verified. merged: true when the proof folded the visitor into a contact that was already verified. Distinct from identified: that fires on claim, this fires on proof.
message:sent{ conversationId, messageId, senderType: 'visitor' }
message:received{ conversationId, messageId, senderType: 'agent' | 'ai' | 'system' }
unread:change{ unreadCount }Fires when the count changes, not at boot.
campaign:shown{ campaignId, campaignName, stepId }A campaign card appeared, on the page or at the top of Webchat opened over it. Fires once per card.
campaign:acted{ campaignId, campaignName, stepId, element: 'button' | 'reply' | 'card', buttonId, buttonLabel }The visitor pressed a button (buttonId and buttonLabel, the words they read), wrote in the reply field, or pressed the card itself.
campaign:closed{ campaignId, campaignName, stepId }The visitor closed the card.
campaign:converted{ campaignId, campaignName, goal: 'conversation' | 'button' | 'page' | 'event' }The campaign's goal was reached within its window after the card. Fires once, in one tab of the visitor's browser, possibly on a later page or a later visit.

Listeners can be registered at any time, including before the widget has booted; the returned unsubscribe works either way. Every event is also dispatched on window as a CustomEvent named assistify:<event> (for example assistify:campaign:shown), its payload in detail, so a tag manager can listen without waiting for the widget.

Campaign events fire only for cards your workspace records, never in the dashboard's preview. They carry no visitor or contact identifier and none of the words the visitor typed. campaignName is the name the campaign has in your workspace, and stepId names the card of a campaign with several steps.

Campaign events in Google Analytics

With Google Tag Manager on your website, add a Custom HTML tag that fires on all pages:

<script>
  window.dataLayer = window.dataLayer || [];
  ['campaign:shown', 'campaign:acted', 'campaign:closed', 'campaign:converted'].forEach(function (name) {
    window.addEventListener('assistify:' + name, function (event) {
      window.dataLayer.push(Object.assign({ event: 'assistify_' + name.replace(':', '_') }, event.detail));
    });
  });
</script>

Each campaign event then reaches the data layer as assistify_campaign_shown, assistify_campaign_acted, assistify_campaign_closed or assistify_campaign_converted, with its payload beside it. In Tag Manager:

  1. Create a Data Layer Variable for each field you want in Google Analytics, such as campaignName, buttonLabel and goal.
  2. Create a Custom Event trigger whose event name matches assistify_campaign_.* (with Use regex matching).
  3. Create a Google Analytics: GA4 Event tag on that trigger, with {{Event}} as its event name and the variables as event parameters.

To measure a campaign's goal in Google Analytics, mark assistify_campaign_converted as a key event.

widget.consent.set(true);    // grant
widget.consent.set(false);   // withdraw
widget.consent.get();        // 'granted' | 'denied' | 'unknown'

Flat: window.Assistify.setConsent(true), window.Assistify.setConsent(false), window.Assistify.getConsent().

The visitor ID is persisted by default. Withdrawing deletes the cookie and its stored copies, unsent drafts and the sound and emoji preferences, and falls back to an ID kept for the current tab only. Granting persists the ID again after a withdrawal. A recorded decision counts for 13 months.

Both calls are safe before the runtime has booted: the decision is recorded at once and the boot honors it, so an early withdrawal means the persistent cookie is never written.

The widget also reads the page's IAB TCF v2.2 signal (Purpose 1) once at boot, waiting up to 800 ms for it; a consent platform's answer takes precedence over a recorded decision, and gdprApplies: false counts as granted. A choice made on the banner after the page loaded applies from the next page. consent.get() returns the decision recorded with consent.set(), or 'unknown': it does not report the platform's answer.

To hold all widget network activity until consent, including the loader script, use autoload: false and call widget.load() from your consent platform's grant callback. See SDK → Deferred boot.