JavaScript API
Control the chat widget programmatically from your website's JavaScript. Open the chat from a custom button, hide it based on conditions, or toggle it in response to user actions.
Enable the API
- Go to Dashboard → Chat Settings → JavaScript API
- Toggle the JavaScript API on
- Save settings
Once enabled, the embed script exposes a global window.FloatMessage object with the methods below.
Available Methods
| Method | Description |
|---|---|
| FloatMessage.showChat() | Shows the chat bubble (if previously hidden) |
| FloatMessage.hideChat() | Hides the chat bubble and closes the panel |
| FloatMessage.openChat() | Shows the bubble and opens the chat panel |
| FloatMessage.closeChat() | Closes the chat panel (bubble stays visible) |
| FloatMessage.toggleChat() | Toggles the chat panel open or closed |
| FloatMessage.setCustomData(data) | Send custom key-value data for the visitor. Available as ${key} template variables in AI instructions and in webhook payload as visitor.customData |
| FloatMessage.on(event, callback) | Listen for events. Supported events: cta:click (visitor clicks any element with the fm-cta class — detail: { messageId, template }) and appointment_booked (visitor confirms a booking via the book-appointment template — detail: { messageId, bookingId, slotStart, slotEnd }) |
| FloatMessage.off(event, callback) | Remove a previously registered event listener |
Examples
Open Chat from a Custom Button
<button onclick="FloatMessage.openChat()">
Need help? Chat with us
</button>Toggle Chat from a Navigation Link
<a href="#" onclick="event.preventDefault(); FloatMessage.toggleChat()">
Support
</a>Show Chat After a Delay
<script>
// Hide chat initially, then show after 10 seconds
setTimeout(function() {
if (window.FloatMessage) {
FloatMessage.showChat();
}
}, 10000);
</script>Open Chat Based on User Action
// Open chat when a visitor scrolls to the pricing section
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && window.FloatMessage) {
FloatMessage.openChat();
observer.disconnect();
}
});
observer.observe(document.getElementById("pricing"));Pass Custom Data for AI Personalization
<script>
// Pass visitor context to the AI agent and webhook
FloatMessage.setCustomData({
userPlan: "enterprise",
cartTotal: "249.99",
accountAge: "2 years"
});
// These become ${userPlan}, ${cartTotal}, ${accountAge}
// in your AI instructions
</script>Set Custom Data After User Login
// After your auth flow completes
function onUserLogin(user) {
if (window.FloatMessage) {
FloatMessage.setCustomData({
userId: user.id,
plan: user.subscription,
company: user.companyName
});
}
}Hide Chat on Specific Pages
<script>
// Hide chat on checkout pages
if (window.location.pathname.startsWith("/checkout")) {
document.addEventListener("DOMContentLoaded", function() {
if (window.FloatMessage) {
FloatMessage.hideChat();
}
});
}
</script>Events
Use FloatMessage.on() to listen for events from your floating messages. Events are available globally — no need to enable the Chat JS API.
CTA Click Event
The cta:click event fires when a visitor clicks any element with the fm-cta CSS class in your message HTML. Add this class to any button or link you want to track as a CTA. When triggered, the message is automatically dismissed.
FloatMessage.on("cta:click", function(detail) {
console.log("CTA clicked!", detail.messageId, detail.template);
});Making a Button a CTA
In your message HTML, add the fm-cta class to any button you want to fire the event:
<button class="fm-btn fm-cta">Accept</button>
<button class="fm-close">Decline</button>Cookie Consent → Load Google Tag Manager
A common use case is using a FloatMessage cookie banner to gate cookie-dependent scripts. When the visitor clicks "Accept" (a CTA), load Google Tag Manager which then fires all your analytics and marketing tags:
<script>
FloatMessage.on("cta:click", function(detail) {
// Only react to the cookie banner
if (detail.template !== "cookie-banner") return;
// Save consent so GTM loads on future pages
localStorage.setItem("fm_cookie_consent", "granted");
// Inject Google Tag Manager
loadGTM();
});
// Load GTM if consent was previously given
if (localStorage.getItem("fm_cookie_consent") === "granted") {
loadGTM();
}
function loadGTM() {
if (window._fmGtmLoaded) return;
window._fmGtmLoaded = true;
// Replace GTM-XXXXXX with your GTM container ID
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');
}
</script>Open Chat from a Floating Message
The Chat CTA template includes a button that opens the chat panel using onclick. You can add this to any custom message template:
<button onclick="if(window.FloatMessage)FloatMessage.openChat()">
Chat with us
</button>This works inside Shadow DOM because onclick handlers execute in the global scope. Requires the JS API to be enabled in Chat Settings.
Remove an Event Listener
function myHandler(detail) {
console.log("Clicked:", detail.messageId);
}
FloatMessage.on("cta:click", myHandler);
// Later, remove it
FloatMessage.off("cta:click", myHandler);Contact Form Handling
The Contact Form template includes built-in form submission handling in the embed script. No JavaScript API setup needed.
How It Works
The embed script detects the fm-form-submit button class inside the Shadow DOM. When clicked:
- Collects all
fm-form-inputelements by theirnameattribute - Validates required fields (highlights invalid fields in red)
- POSTs to
/api/forms/submitwith the message ID and form data - On success, hides the form fields and shows the
fm-form-successelement
CSS Classes
| Class | Element | Purpose |
|---|---|---|
| fm-form-input | input, textarea, select | Form field. Must have a name attribute. |
| fm-form-submit | button | Triggers form submission when clicked. |
| fm-form-fields | div | Container for form fields. Hidden after successful submission. |
| fm-form-success | div | Shown after successful submission (initially hidden with display:none). |
Submissions are stored in the database and visible in Dashboard → Submissions. If a webhook URL is configured on the message, the data is also forwarded via POST.
Notes
FloatMessage.on()andFloatMessage.off()are always available — they work even without enabling the Chat JS API.- Chat methods (
openChat,hideChat, etc.) require the Chat JS API to be enabled in Chat Settings. - The
FloatMessageobject is available after the embed script loads. If calling early, checkwindow.FloatMessageexists first. - All methods are safe to call at any time — they handle edge cases like the panel already being open or the bubble already being hidden.
- The API works on both desktop and mobile. On mobile,
openChat()opens the full-screen chat panel. - When a CTA button is clicked, the message is automatically dismissed. The dismiss behavior follows your configured dismiss settings (session, duration, or permanent).