Widget SDK
The widget SDK is the window.Ferndesk command function that the embed snippet installs on your page. Call it to start the widget, open views, sign visitors in and react to what happens in the widget.
Install the widget
Copy your widget's snippet from its Install section in Ferndesk. It has two parts: the first loads the SDK, the second starts your widget with its ID. Always copy the full snippet from Ferndesk. It looks like this:
<!-- Step #1. Install the Ferndesk SDK -->
<script>
!function(e,t){ ... }(window,document);
</script>
<!-- Step #2. Initialize the widget -->
<script>
Ferndesk("init", { widgetId: "YOUR_WIDGET_ID" })
</script>Paste it right before the closing </body> tag of the pages that should show the widget. Changes saved in Ferndesk reach the widget without touching this code.
Single-page apps
Load the SDK once, in your root layout or app shell. The widget stays on the page while visitors move between routes, so you don't call init again on navigation. Call init again only to change an option it sets.
import { useEffect } from 'react';
export function FerndeskWidget() {
useEffect(() => {
if (document.getElementById('ferndesk-sdk')) return;
const script = document.createElement('script');
script.id = 'ferndesk-sdk';
script.src = 'https://static.ferndesk.com/dist/sdk.js';
script.async = true;
script.onload = () => {
window.Ferndesk('init', { widgetId: 'YOUR_WIDGET_ID' });
};
document.body.appendChild(script);
}, []);
return null;
}Render the React component once, near the root of your app.
Sign visitors in
When your app knows who the visitor is, pass a JWT signed with the Signing secret from Customer sign-in in your Ferndesk developer settings. The widget then shows content for that customer and keeps their chats under their account. The claims the token holds are in Sign readers in with JWT or OIDC.
Ferndesk('init', { widgetId: 'YOUR_WIDGET_ID', jwt: tokenFromYourServer });
// When the user signs in after the page loaded:
Ferndesk('identify', { jwt: tokenFromYourServer });
// When the user signs out:
Ferndesk('logout');Calling logout clears the visitor's chats and contact form from that browser, so the next person on a shared computer doesn't see them. For every command and option, see the Widget SDK reference.
Ferndesk('init', { widgetId: 'YOUR_WIDGET_ID' });
Ferndesk('openArticle', { shortId: 'abc123', presentation: 'modal' });Every call passes the command name first, then its arguments. Command names are case-insensitive.
Calls made before the SDK script loads are queued and run in order once it arrives.
An unknown command or an invalid argument logs a warning in the browser console and changes nothing.
Init options
Pass these to Ferndesk('init', { ... }). Only widgetId is required.
Option | Type | What it does | Default |
|---|---|---|---|
| string | Your widget's ID. Without it, init logs a warning and does nothing. | None |
| boolean | Opens the panel when the widget loads. |
|
| boolean | Hides the floating launcher button. Give visitors your own button that calls |
|
| string or null | The visitor's language, such as | Detected from |
| string | Signs the visitor in before the widget mounts. Takes the same token as | Anonymous |
| boolean |
|
|
|
| Matches the widget to your page's theme. | The widget's own setting |
|
| The side of the screen for the launcher and panel on this page. | The dashboard Position |
|
| Distance from the side edge ( | The dashboard margin |
|
| This visitor's override of when a person is offered: | The dashboard setting |
| boolean |
| On |
|
| When an announcement takes the screen. |
|
Calling
initagain removes the widget and mounts a fresh one. The panel closes, the visitor loses their place, andreadyfires again.Single-page apps don't need to call
initon navigation. The widget stays on the page untildestroy, even when your router replaces<body>.An
initwithoutlocalekeeps the language set earlier bysetLocaleor anotherinit.pageContextalso stays until anotherinitsets it.<html data-ferndesk-context="off">has the same effect aspageContext: false.With
jwt, the widget waits up to 3 seconds for sign-in before it mounts. After that it mounts anonymous and picks up the identity when sign-in finishes.Changelog announcements only reach signed-in visitors, for entries announced since their last visit. Anonymous visitors and first-time visitors are never interrupted.
Example: open the widget from your own button instead of the launcher.
<button onclick="Ferndesk('open')">Get help</button>
<script>
Ferndesk('init', { widgetId: 'YOUR_WIDGET_ID', hideLauncher: true });
</script>Position and offset
position and offset replace the dashboard's Position and margin on this page only, so each environment gets the placement its code sets.
Ferndesk('init', {
widgetId: 'YOUR_WIDGET_ID',
position: 'left',
offset: { x: 'calc(var(--sidebar-width, 264px) + 16px)', y: 24 }
});Each part is optional. A side or axis you leave out keeps the dashboard value.
Offsets have no upper limit, so the widget can sit beside your app's sidebar or above a footer bar.
A CSS length can use your own custom properties, but only ones set on
:root,htmlorbody. The widget's container is a child of<body>. Give the variable a fallback, as in the example. If the length can't be resolved, that axis uses the dashboard margin.Invalid values are skipped with a warning: an unknown side, a negative number, or a string that isn't a CSS length (such as
auto). The rest of the call still applies.The widget stays usable. The side offset leaves at least 5rem of the viewport for the launcher, the bottom offset leaves at least 24rem, and the open panel shrinks to fit.
On screens under 640px wide the open panel fills the screen, so offsets only move the launcher.
Change placement later with
setLayout. These options are the supported way to place the widget. The widget's internal--fd-*CSS variables are not public and can change.
Commands
Commands that return a value return it straight away, except identify and logout, which return promises.
Open and close
Command | Arguments | What it does |
|---|---|---|
| None | Opens the panel. It doesn't bring back a widget hidden with |
| None | Closes the panel and any floating article. |
| None | Opens the panel if it is closed and closes it if it is open. If a floating article is showing, closes the article instead. |
| None | Hides the launcher and the panel, and closes any floating article. |
| None | Brings back a widget hidden with |
| None | Opens the panel on the home screen. |
| None | Returns |
Every open... command except open itself, and search, also brings back a widget hidden with hide.
Navigate to content
Command | Arguments | What it does |
|---|---|---|
| Optional section slug, as a string or | Opens the docs view, scrolled to that section when you pass one. |
|
| Opens a collection. |
|
| Opens an article. |
|
| Opens the widget with search results for |
|
| Opens an API reference. |
|
| Opens one operation in an API reference. |
'inline' shows the article next to the element you pass as anchor. Without an anchor, it falls back to 'modal'.
Ferndesk('openArticle', {
shortId: 'billing-faq',
presentation: 'inline',
anchor: document.getElementById('billing-info')
});Your AI agent, contact and Support conversations
Command | Arguments | What it does |
|---|---|---|
| None | Opens the chat with your agent. With Support on, it starts a conversation. |
| Optional | Opens the contact method set for the widget: the contact form, a link, a chat tool or WhatsApp. A |
| None | Opens the Messages tab with the visitor's conversations. Works when the widget has its Messages tab. |
| Conversation ID as a string, or | Opens that conversation. If the ID isn't one of the visitor's conversations, it opens Messages. Works when the widget has its Messages tab. |
| Optional text, as a string or | Starts a conversation with the text in the composer. The visitor reads it and sends it. Works when the widget has its Messages tab. |
| None | Returns how many team replies the visitor hasn't read. Returns |
|
| Changes this visitor's escalation strategy, as the |
Without Support,
openMessages,openConversationandopenNewMessagelog a warning and open Home.The strategies match the dashboard's Offer a person options on Your agent > Customize > Handoff:
'ai_decides'is When needed,'always_visible'is Always visible, and'none'is Off.Use a per-visitor strategy to keep a contact button visible for customers with priority support, or to stop offering a person on a plan that has none.
Ferndesk('init', {
widgetId: 'YOUR_WIDGET_ID',
jwt,
escalation: { strategy: user.plan === 'enterprise' ? 'always_visible' : 'ai_decides' }
});Identity and prefill
Command | Arguments | What it does |
|---|---|---|
|
| Signs the visitor in after the widget has mounted, or refreshes their session. Returns a promise with the result. |
| None | Ends the help center session the widget started. Forgets the visitor's Support chat, conversation list, prefill and unsent draft in this browser. The widget stays on the page for the next, anonymous visitor. |
|
| Fills empty fields in the contact form. A call before |
Call Ferndesk('logout') when your user signs out. Without it, the next person on a shared computer sees the previous user's conversations.
identify resolves to { identified: true, user } or { identified: false, reason }.
const result = await Ferndesk('identify', { jwt });
if (!result.identified) {
console.warn('Ferndesk sign-in failed:', result.reason);
}Reason | Meaning |
|---|---|
| No JWT was passed. |
|
|
| The help center refused the JWT. |
| No answer came back, for example because the visitor is offline. |
| A later |
A rejected JWT for a different user signs out the user who was signed in before, so the widget never shows the last person's data.
While an
identifyis in progress, Support waits for it, so the visitor's chat starts under the signed-in user.When the widget's help center session lapses,
identityExpiredfires. Mint a fresh JWT and callidentifyagain.
A signed-in visitor's contact form starts with the name and email from their JWT. prefill fills the same fields for visitors without a JWT, and its values win over the JWT's. Add lockNameAndEmail: true to show the name and email as one read-only row.
Ferndesk('prefill', {
name: user.fullName,
email: user.email,
lockNameAndEmail: true
});Each call replaces the previous one, so pass the name and email every time.
Prefill only fills empty fields. It never replaces what the visitor typed, including an unsent message from earlier.
Name and email stay after a send. A prefilled
subjectandmessagebelong to one message and clear once it is sent.The email also fills the email card a Support chat shows after a handoff. The visitor still presses send.
For a signed-in visitor,
Ferndesk('prefill', { lockNameAndEmail: true })locks the name and email from their JWT.Only a name that isn't blank and an email that looks valid are locked. Anything else stays editable, so the visitor can always send.
The lock applies to the form only. The contact endpoint still accepts whatever is posted.
When
identifysigns in a different person, the widget drops the prefill, the lock, any unsent message and the open screens. Callprefillfor the person who signed in afterawait Ferndesk('identify', { jwt })resolves.
Appearance and layout
Command | Arguments | What it does |
|---|---|---|
| A language code, or | Changes the widget's language. |
|
| Changes the color scheme to match your page. |
|
| Replaces this page's placement, with the same rules as |
Calling setLocale with the language the widget already shows does nothing, so you can call it on every route change without disturbing an open panel.
Changelog
Command | Arguments | What it does |
|---|---|---|
| Optional short ID, as a string or | Opens the changelog feed. Without an ID, it opens the visitor's visible changelog with the latest announcement. Opening a changelog marks its entries as seen. |
| Optional | Shows the announcement deck when the visitor has unseen entries. Otherwise it does nothing. Use it with |
| None | Returns |
{ replay: true } is for your own "What's new" button. It always answers the click:
A visitor with unseen entries gets the deck the automatic trigger would show.
A visitor who has seen everything, or has no seen record yet, gets the latest 3 announced releases.
It plays for signed-out visitors, with announcements turned off, and with either trigger. It brings back a hidden widget.
If no changelog the visitor can read has an announced release, it opens the changelog feed instead.
whatsNewButton.addEventListener('click', () => {
Ferndesk('showChangelogAnnouncement', { replay: true });
});
Ferndesk('on', 'changelogStatus', ({ available, unseen }) => {
whatsNewButton.hidden = !available;
whatsNewButton.classList.toggle('has-news', unseen);
});Event subscriptions
Command | Arguments | What it does |
|---|---|---|
| Event name, handler function | Subscribes the handler and returns a function that unsubscribes it. Works before the SDK script loads and before init. |
| Event name, handler function | Removes a handler added with on. |
const off = Ferndesk('on', 'quickLinkClick', (link) => {
if (link.url?.includes('report-bug')) {
link.preventDefault();
openMyBugReportForm();
}
});
// later
off();Lifecycle
Command | Arguments | What it does |
|---|---|---|
| Options object | Mounts the widget. See Init options. |
| None | Removes the widget from the page. Call |
Events
Subscribe with Ferndesk('on', event, handler). The handler receives the payload below.
Event | Fires when | Payload |
|---|---|---|
| The widget has loaded its configuration and can render. Once per init. |
|
| The panel comes on screen, from the launcher, a command, or | None |
| The panel leaves the screen: the visitor closes it, or you call | None |
| A visitor clicks a custom link on the home screen. |
|
| The changelog view opens, by any route. |
|
| The widget boots, and whenever changelog state changes. |
|
| The number of unread team replies changes, and once when the widget boots. |
|
| The visitor's first message starts a Support conversation. |
|
| The visitor sends a message, the first one included. |
|
| Your AI agent starts offering a person in a conversation. |
|
| The visitor asks for a person, from a contact prompt in the chat or the contact link on the home screen. |
|
| The widget's help center session lapses. |
|
readyandunreadCountChangereplay once to a handler added after they fired. Other events don't replay.openandclosefire only on a change. Floating articles are separate from the panel and don't fire them.In
quickLinkClick,preventDefault()stops the widget from following the link so your page can act instead. Clicks with a modifier key or the middle button keep the browser's behavior and don't fire the event.changelogStatus.availableisfalsewhen the visitor can't see any changelog.unseenistruewhile an announced entry is newer than the visitor's last visit, and is alwaysfalsefor anonymous visitors.reasonis one of'no_answer','partial','user_request','sensitive','negative_feedback'or'frustrated'. InescalationRequestedit isnullwhen the visitor used the home screen link.escalationOfferedfires once per reason and trigger per conversation. The always-visible contact button is not an offer and doesn't fire it.
Handle escalationRequested
By the time escalationRequested fires, Your AI agent has written the handoff message in draft and subject. draft is an empty string when Draft a handoff summary is off or there is no conversation to summarize. source is 'assistant' or 'home'. channel says where the widget will send the visitor: { type: 'form' }, { type: 'link', url } or { type: 'integration', platform }. A WhatsApp number arrives as a link to https://wa.me/<number>. Your handler picks one of four outcomes.
Handler does | Widget does |
|---|---|
Nothing | The configured handoff, as if there were no handler. |
| Shows a sheet inside the widget with your copy and options. |
| Hands off straight away, optionally to another channel or with another message. |
| Nothing. Your page owns the next step and can call |
Ferndesk('on', 'escalationRequested', (event) => {
if (user.plan === 'basic') {
event.present({
title: 'Talk to our team',
message: 'Priority replies come with the Business plan.',
actions: [
{ label: 'Upgrade', url: '/billing/upgrade', target: 'self' },
{ label: 'Contact support anyway', action: 'continue' }
]
});
return;
}
if (event.trigger === 'billing_dispute') {
event.continue({
channel: { type: 'link', url: 'mailto:[email protected]' },
draft: `Plan: ${user.plan}\n\n${event.draft}`
});
}
});A sheet action is one of:
{ label, action: 'continue', channel, draft, subject }for the handoff, optionally rerouted;{ label, url, target }for an http(s), mailto or same-site link, wheretarget: 'self'navigates your page; or{ label, onClick }to run your code while the widget stays open.Each action takes an optional
descriptionandstyle: 'primary' | 'secondary'. The first action is primary by default.At most four actions show. Unsafe URLs are dropped with a console warning. Leave out
actionsto offer only the default handoff.To decide later, call
event.preventDefault()inside the handler, thenpresent()orcontinue()when you're ready. Only the firstcontinue()counts. A request goes stale when the visitor asks again or the widget is destroyed.continue()can reroute to{ type: 'link', url }or{ type: 'integration', platform }. A mailto link gets the draft as subject and body, awa.meorapi.whatsapp.comlink gets it as the chat message, and any other page has it copied to the clipboard.Integration platforms are
crisp,helpscout,intercom,zendesk,pylon,plainandchatwoot. If the chat tool isn't on the page, the widget falls back to its configured contact method.The contact form sends to the inbox set in the dashboard, so it can only be the default channel, never a reroute target.
triggeris the key of the handoff trigger your agent matched, ornull. Define triggers on Your agent > Customize > Handoff, under When to hand off > Handoff triggers: a key such asbilling_disputeand a plain-language description of when it applies.
Data attributes
Add these attributes to any element on your page to open the widget on click, without writing JavaScript. They work once init has run.
Attribute | What it opens |
|---|---|
| The docs view. An optional value is a section slug to scroll to. |
| An article inside the widget panel. |
| An article in a sidebar. |
| An article in a modal. |
| An article inline, next to the clicked element. |
| An API reference. |
| One operation in an API reference. |
| The changelog feed. An optional value is a changelog short ID. Without one, the widget picks the same changelog as openChangelog. |
<button data-ferndesk-docs="billing">Billing help</button>
<a data-ferndesk-article-modal="abc123">Pricing FAQ</a>
<button data-ferndesk-api-operation="public-api/create-user">Create a user</button>
<button data-ferndesk-changelog>What's new</button>Article attributes also accept an article ID that starts with
art_.Only plain left clicks open the widget. Clicks with Cmd, Ctrl, Shift or Alt keep the browser's behavior.
While the visitor has unseen changelog entries, the SDK adds a dot to each
data-ferndesk-changelogelement. Restyle it with CSS on.Ferndesk_BadgeContainer .Ferndesk_Badge, or hide it and build your own badge fromchangelogStatus.
Supported languages
The widget's own interface ships in these languages. Use the codes with locale and setLocale.
Code | Language |
|---|---|
| English |
| French |
| Spanish |
| German |
| Dutch |
| Portuguese |
| Italian |
| Japanese |
| Korean |
| Chinese |
| Swedish |
| Norwegian |
| Danish |
| Finnish |
| Turkish |
| Estonian |
Any BCP 47 tag works. The region is dropped, so
pt-BRis Portuguese, andnbandnnmap tono.A code the widget has no strings for is skipped, and the widget tries the next source:
<html lang>, then the browser language.The widget shows a language only when your help center has it turned on. Otherwise it shows the help center's default language. Your AI agent searches and links articles in the same language.
Content Security Policy
If your site sends a Content Security Policy, add these addresses to it. Rows that start with "Only some widgets" are needed only when your widget uses that feature.
Directive | Add | What it is for |
|---|---|---|
| Your page's nonce on the snippet, or | The SDK and the widget's other scripts. The snippet copies its nonce onto them. Without a nonce, allow the host and a hash of the snippet. |
|
| The widget adds its styles inside its shadow root as |
|
| The widget's fonts. |
|
| Widget settings, your AI agent, Support chat and the changelog. |
| Your help center's address: | Docs, search and articles, which the widget reads from your help center. |
|
| Widget analytics. If you block it, visitors see no difference, but your widget reports stay empty. |
|
| Files a visitor attaches to a Support chat. They upload straight to Cloudflare R2 storage. |
|
| Logos, team photos and images in articles and changelog entries. |
|
| Only some widgets: a widget header with an Unsplash background. |
|
| Only some widgets: Phosphor icons on widget links or cards. |
|
| Only some widgets: HTML embed blocks in articles and changelog entries. |
| The video hosts your articles embed, such as | Only some widgets: video blocks in articles. |
| Any other host your articles' images use | Only some widgets: images imported from another help center can keep their old address. |
A full policy for a widget whose help center is at https://help.example.com, with a nonce on the snippet:
script-src 'nonce-<your nonce>';
style-src 'self' 'unsafe-inline' https://fonts.bunny.net;
font-src 'self' https://fonts.bunny.net;
img-src 'self' https://files.ferndesk.com;
connect-src 'self' https://engine.ferndesk.com https://help.example.com https://capture.ferndesk.com https://ferndesk-customer-private.4171fd55e47471c8b93a53e16a869f80.r2.cloudflarestorage.com;When the chat starts, the browser reports one script-src 'unsafe-eval' violation. It is harmless: the chat checks whether it may compile validators and works without them. Don't add 'unsafe-eval'.
A chat tool the widget hands off to, such as Intercom, Crisp or Plain, needs its own addresses. They are in that tool's documentation.
If the widget does not appear
Check that the snippet is on the page: open your browser's developer tools and look for a script with the ID
ferndesk-sdk.In the Network tab, check that
https://static.ferndesk.com/dist/sdk.jsloads. Ad blockers and strict firewalls can block it.If your site sends a Content Security Policy, check that it allows every address in Content Security Policy above. If the launcher shows but the widget stays empty, the console names the blocked address.
If the console says the SDK is on the page twice, remove the second copy. This often happens when a tag manager and a hard-coded snippet both load it. The copy that loaded first stays in charge.