Robofy API
HomeChangelog
HomeChangelog
Visit Website
Sign In
Create an account
  1. Start Guide
  • Start Guide
    • Overview
    • Architecture
    • Authentication
    • Changelog
    • Function Tool Call
    • Chat Widget Custom CSS Classes
    • Agent Widget JavaScript SDK
  • Robofy API
    • Chat
      • Generate Client Token (Handshake)
      • Send Message (Streaming)
      • Send Message (Non Streaming)
      • Send WhatsApp Message
    • Chatbot / Agent
      • List Agents
      • Create Agent
      • Retrieve Agent
      • Update Agent
      • Delete Agent
      • Delink Asset
      • List Linked Assets
      • Delete Widget Tab
    • Account
      • Retrieve Account Details
      • Update Account Details
      • Retrieve Account Limit
    • Prompt & Persona
      • Update System Prompt
      • Retrieve Agent Settings
      • Update Persona
      • Retrieve Persona
    • Inbox
      • List Sessions
      • List Session Messages
    • Project
      • Create Project
      • List Projects
      • Update Project
      • Retrieve Project
    • Leads
      • List Leads
    • Content
      • Add Website
      • Get Crawl Status
      • Add Text Content
      • Add File
    • Stats
      • Stats
    • License
      • Create License
      • List License
      • Update License
      • Retrieve License
      • Delete License
      • Update License Limit
    • Partner
      • Onboard
    • Schemas
      • Account
      • AccountDetailDto
      • Address
      • AgentCredentialInsertResponseDto
      • AgentCredentialRequestDto
      • AgentCredentialResponseDto
      • AgentDataPoint
      • AgentLeadCapture
      • AgentLeadReportDto
      • AgentLinkageDto
      • AgentMcpServerDto
      • AgentMcpServerInsertResponseDto
      • AgentMcpServerRequestDto
      • AgentMcpServerUpdateRequestDto
      • AgentPromptVersionDto
      • AgentSessionListDto
      • AgentSessionListItemDto
      • AgentStatsDto
      • AgentThemeDto
      • AgentThemeListDto
      • AgentToolLinkageInsertResponseDto
      • AgentToolLinkageRequestDto
      • AgentWhatappIntrgrationResponse
      • AgentWhatsAppLinkageDto
      • Button
      • CarouselCard
      • CategoryStats
      • ChatBotDetailsDto
      • ChatBotDetailsRequest
      • ChatBotDetailsUpdateRequest
      • ChatbotAISettingsDto
      • ChatbotAISettingsRequest
      • ChatbotAdvanceSettingsDto
      • ChatbotAdvanceSettingsRequest
      • ChatbotAppearanceSettingsDto
      • ChatbotAppearanceSettingsRequest
      • ChatbotAssetDelinkDto
      • ChatbotAssetLinkageDataDto
      • ChatbotAssetLinkageDelinkRequest
      • ChatbotAssetLinkageDetailsDto
      • ChatbotAssetLinkageDto
      • ChatbotAssetLinkageRequest
      • ChatbotTextLinkageRequest
      • ClientData
      • CommonResponse
      • Component
      • Contact
      • ContactName
      • CrawlStatusDto
      • CrawlWebsiteRequest
      • CreateOrUpdateProjectRequest
      • CreatePhoneNumberRequest
      • CreateTemplateRequest
      • CreateWebhookConfigRequest
      • DeLinkWhatsAppRequest
      • Email
      • Error
      • ErrorResponse
      • Example
      • FailureStats
      • FailureStatsDataPoint
      • FormField
      • GoogleSheetDto
      • GoogleSheetIntegrationRequest
      • InboxChatDto
      • InboxDto
      • InboxMessage
      • InboxSession
      • IntelligentMetricsDto
      • Interactive
      • InteractiveAction
      • InteractiveBody
      • InteractiveButton
      • InteractiveFooter
      • InteractiveHeader
      • InteractiveMedia
      • InteractiveProductItem
      • InteractiveProductSection
      • InteractiveReply
      • InteractiveRow
      • InteractiveSection
      • LeadCaptureForm
      • LeadData
      • LeadDataField
      • LeadFormData
      • LeadReport
      • LicenseCreateRequest
      • LicenseDto
      • LicenseLimitRequest
      • LicenseUpdateRequest
      • LimitedTimeOffer
      • LinkWhatsAppRequest
      • LinkedCredentialDto
      • LinkedMcpServerDto
      • Location
      • Media
      • MessageMetaData
      • MessageRequest
      • MessageResponse
      • MessageStats
      • MessageStatsDataPoint
      • MessageTemplate
      • NamedParameter
      • OrgLimitDto
      • Organization
      • PaginatedWebhookLogsResponse
      • Part
      • PartnerClientSession
      • PartnerClientSessionDto
      • Phone
      • PhoneNumberRequest
      • PhoneVerifyCodeRequest
      • PhoneVerifyRequest
      • PlatformStats
      • ProjectDetailDto
      • ProjectWABADetail
      • Reaction
      • ReadTypingIndicatorRequest
      • RecentInsightDto
      • Response
      • SessionInsightItemDto
      • SessionInsightsDto
      • SessionMetaDto
      • SessionMetricsDto
      • SessionSummaryDetailDto
      • StartUrl
      • SubcribedAppsRequest
      • SupportedApp
      • TemplateAction
      • TemplateButtons
      • TemplateCarousel
      • TemplateComponent
      • TemplateCurrency
      • TemplateDateTime
      • TemplateLimitedTimeOffer
      • TemplateMedia
      • TemplateParameter
      • TemplateProductItem
      • TemplateSection
      • TemplateTapTargetConfiguration
      • Text
      • ThemeMetaDto
      • TypingIndicator
      • UpdateOnboardStatusRequest
      • UpdateOnboardStatusResponseDto
      • UploadMedia
      • Url
      • WABADetail
      • WABADto
      • Webhook
      • WebhookConfigDto
      • WebhookConfiguration
      • WebhookLogDto
      • WebsiteDto
      • WhatsAppBusinessApiData
      • WhatsAppBusinessProfile
      • WidgetIntegration
  1. Start Guide

Agent Widget JavaScript SDK

TIP
Host-page JavaScript API for agent-widget.js.
Related: Function Tool Call Setup for signed-in visitor auth (setAuth), website context (setContext), and {host.*} tokens.
This page documents the public API exposed by agent-widget.js on the host (customer-facing) page.
AudienceDifficulty
Website / app integratorsIntermediate

When is AgentWidget available?#

INFO
window.AgentWidget is created as soon as the embed script runs successfully. Commands called before the iframe is ready are queued and flushed on ready.
ConditionResult
Script tag includes valid data-pid and data-cid, and src loadswindow.AgentWidget exists
Script missing data-pid / data-cid, or invalid srcAPI is not created (console warning)
Immediately after script loadMethods exist; calls to the iframe are queued until ready
After the ready event / AgentWidget.isReady() === trueIframe is ready; queued commands flush
After AgentWidget.destroy()API no longer works on that page
WhatsApp or admin builderNot available - host SDK runs only on the embedded web page
WARNING
Do not call AgentWidget methods until the script has loaded. Guard with window.AgentWidget (see safe pattern below).

Embed the script#

AttributeRequiredDescription
srcYesURL of agent-widget.js on your app origin
data-pidYesProject ID
data-cidYesChatbot / agent ID
After load, the script handshakes with the widget backend, renders the chat bubble, and exposes window.AgentWidget.

Safe ready pattern#

NOTE
You may call setAuth, setContext, and identify before ready. The SDK queues those messages. Prefer waiting for ready when you need to know the chat session can use them.

Global object#

Global: window.AgentWidget
PropertyTypeDescription
versionnumberSDK version (currently 2)
projectIdstringFrom data-pid
chatbotIdstringFrom data-cid

Lifecycle#

MethodPurpose
AgentWidget.open()Opens the chat panel
AgentWidget.close()Closes the chat panel
AgentWidget.toggle()Toggles open / closed
AgentWidget.destroy()Removes bubble, iframe, tips, listeners, and pending work

State#

MethodReturnsPurpose
AgentWidget.isOpen()booleanWhether the panel is open
AgentWidget.isReady()booleanWhether the iframe has signaled READY
AgentWidget.getState()object{ open, ready, initialized, destroyed, appearance }

Events#

The SDK has an in-JS emitter and also dispatches DOM CustomEvents named AgentWidget:<eventName> on window.

Subscribe#

MethodPurpose
AgentWidget.on(eventName, handler)Subscribe; returns an unsubscribe function
AgentWidget.once(eventName, handler)Subscribe once; returns unsubscribe
AgentWidget.off(eventName, handler)Remove a handler

Common events#

EventWhen
initHandshake / appearance loaded
readyIframe READY; safe for iframe-dependent work
open / closePanel opened / closed
destroyAfter destroy()
resizeDesktop width changed via setWidth / resetWidth
request_identityIframe asks for current logged-in user
require_loginAgent asks the host to show login
requestIframe needs a host action (e.g. login tool); respond with sendResponse
(custom)Any event name the iframe or host emits

Host commands (page to widget)#

MethodPurpose
identify(user)Send user profile for personalization (not a substitute for auth)
setAuth(auth)Set visitor auth used for signed-in Function Tool Calls and gated flows
clearAuth()Clear visitor auth (logged out)
setContext(context)Page / app context for {host.*} tokens in Function Tool Call
setRuntimeContext(context)Internal / advanced runtime context channel
sendMessage(text, meta?)Send a user message into the chat
prefillMessage(text, options?)Prefill the composer (options.focus defaults to true)
clearInput()Clear the composer text
emitEvent(name, payload?)Emit a custom event into the widget runtime
resetSession()Clear / rotate the conversation session
setWidth(width)Desktop panel width (mobile stays full screen)
resetWidth()Reset desktop width to the SDK default

Identity vs auth vs context#

APIUse forFunction Tool Call
identify(user)Display name, email, CRM id for personalizationDoes not unlock signed-in visitor tools by itself
setAuth({ kind, ... })Access token / credentials for APIs acting as the visitorRequired for Signed-in visitor tools
clearAuth()LogoutSigned-in visitor tools are omitted until auth is set again
setContext({ ... })Non-secret page values (project_id, store_id, ...)Becomes {host.key} after you list keys under From your website
WARNING
Do not put secrets in setContext. Use setAuth for visitor tokens, or stored credentials in Function Tool Call for shared API keys.

Auth shapes#

Bearer token (most common)
Basic auth
API key header
API key query
Custom headers
Cookie-based auth

Context example (Function Tool Call)#

In the tool builder, add those keys under From your website, then use {host.project_id} (and so on) in the URL, headers, query, or body.
See Function Tool Call Setup for sample use cases.

Other examples#

Identity and login flows#

Initial identity (request_identity)
When the iframe loads, listen and reply with the current user (or null if logged out):
For signed-in Function Tool Calls, also call setAuth with the access token when the user is logged in (on page load and after login / refresh).
Require login (require_login)
When the agent needs the visitor to sign in:

Iframe to host requests#

When the agent needs the host page to do something (for example login), the SDK emits request. Reply with sendResponse.
AgentWidget.sendResponse(requestId, payload?, success?, error?)
ArgumentTypeDescription
requestIdstringFrom the request event
payloadanySuccess payload
successbooleanDefaults to true
errorobject or nullFailure details

Recommended integration#

1
Embed the script
Add agent-widget.js with data-pid and data-cid on the host page.
2
Wait for ready
Use AgentWidget.once("ready", ...) or whenAgentWidgetReady.
3
Set identity, auth, and context
Call identify, setAuth, and setContext when the visitor session and page context are known.
4
Handle login events
Listen for request_identity, require_login, and request as needed by your product flows.
5
Open the widget from your UI
Call AgentWidget.open() from buttons or other triggers.
NOTE
For Function Tool Call setup (inputs, auth modes, {host.*} mapping), see Function Tool Call Setup.

Summary#

CategoryAPI
AvailabilityScript with data-pid + data-cid creates window.AgentWidget; wait for ready when needed; gone after destroy()
Lifecycleopen, close, toggle, destroy
StateisOpen, isReady, getState
Eventson, once, off
AuthsetAuth, clearAuth
ContextsetContext, setRuntimeContext
Identityidentify; events request_identity, require_login
ChatsendMessage, prefillMessage, clearInput, resetSession
LayoutsetWidth, resetWidth
Host repliessendResponse (to request events)
CustomemitEvent
Modified at 2026-08-13 08:20:28
Previous
Chat Widget Custom CSS Classes
Next
Generate Client Token (Handshake)
Built with