JavaScript SDK & JWT Webchat Reference
When the /webchat/widget.js loader script runs on your website, it exposes a global window.MahadataChat object to control the widget window, identify signed-in customers, switch the interface language, and register event listeners or message interceptors.
Loader Script Installation
Section titled “Loader Script Installation”Paste the following snippet before the closing tag </body>:
<script src="https://<PORTAL_ORIGIN>/webchat/widget.js" data-widget-id="<WIDGET_UUID>" async></script>Optional attributes on the <script>:
| Attribute | Explanation |
|---|---|
data-widget-id | Webchat widget UUID (required). |
data-locale | Initial widget language (id, en, or zh). |
data-identity-token | Optional JWT HS256 token to authenticate the visitor immediately on initial load. |
Method window.MahadataChat
Section titled “Method window.MahadataChat”Window & Visibility Controls
Section titled “Window & Visibility Controls”| Method | Description |
|---|---|
MahadataChat.open() | Opens the chat window and resets the unread message counter (unread badge) to 0. |
MahadataChat.close() | Closes the chat window back to the launcher. |
MahadataChat.toggle() | Opens the window if it is currently closed, or closes it if it is currently open. |
MahadataChat.show() | Re-shows the launcher button and widget window after they have been hidden with hide(). |
MahadataChat.hide() | Hides all widget elements (including the launcher button and proactive greeting) from the page. |
MahadataChat.destroy() | Removes the widget DOM elements from the page (useful during unmount in an SPA application). |
// Open the chat window when a custom help button is clickeddocument.getElementById("help-btn")?.addEventListener("click", () => { window.MahadataChat.open();});Identity, Language & Message Drafting
Section titled “Identity, Language & Message Drafting”| Method | Description |
|---|---|
MahadataChat.identify(jwtToken) | Sends an HS256 JWT token to the Webchat session to associate the visitor with a verified contact. |
MahadataChat.setLocale(locale) | Dynamically changes the chat interface language ("id", "en", or "zh"). |
MahadataChat.sendDraft(text) | Fills the message input field inside the chat window and opens the window automatically. |
MahadataChat.getUnreadCount() | Returns the current unread message count (number). |
// Mengubah bahasa dan mengisi draf pertanyaanwindow.MahadataChat.setLocale("id");window.MahadataChat.sendDraft("Halo, saya ingin menanyakan status pesanan #INV-1024");Event Listener (on / off)
Section titled “Event Listener (on / off)”Use MahadataChat.on(event, handler) to subscribe to widget lifecycle events, and MahadataChat.off(event, handler) to unsubscribe:
| Event Name | Payload | Description |
|---|---|---|
ready | undefined | Triggered when the chat iframe is ready to communicate. |
open | undefined | Triggered when the chat window is opened. |
close | undefined | Triggered when the chat window is closed. |
message | object | Triggered every time a new message from an agent or bot is received. |
unread | { count: number } | Triggered every time the unread message count changes. |
function onUnreadChange({ count }) { console.log("Pesan belum dibaca:", count);}
window.MahadataChat.on("unread", onUnreadChange);
// Berhenti berlangganan saat tidak diperlukanwindow.MahadataChat.off("unread", onUnreadChange);Message Interceptor (beforeSend & beforeDisplay)
Section titled “Message Interceptor (beforeSend & beforeDisplay)”| Method | Description |
|---|---|
MahadataChat.beforeSend(fn) | Modifies the visitor’s message text before it is sent to the server, or returns null to cancel the sending. Supports both synchronous functions and Promise. |
MahadataChat.beforeDisplay(fn) | Inspects incoming message objects from agents/bots before they are displayed. Return null to hide the message from the visitor’s view. |
// Contoh: Menyamarkan nomor kartu kredit sebelum pesan dikirimwindow.MahadataChat.beforeSend((text) => { return text.replace(/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g, "[REDACTED]");});
// Contoh: Menyembunyikan pesan sistem internal tertentuwindow.MahadataChat.beforeDisplay((msg) => { if (msg?.content?.body?.startsWith("[INTERNAL]")) { return null; } return msg;});Site JWT Format (HS256)
Section titled “Site JWT Format (HS256)”To securely identify logged-in customers (identity mode Optional or Required), create a JWT token using the HS256 using Signing Secret (which can be viewed or rotated on the Identity in the widget settings).
Important: Never store Signing Secret in frontend/browser code. Generate the JWT token on your backend server and send the signed token to the user’s browser.
JWT Payload Claims
Section titled “JWT Payload Claims”| Claim | Type | Required | Description |
|---|---|---|---|
sub (or external_id) | string | Yes | Unique customer ID in your system (for example "user_9812"). |
exp | number | Yes | Token expiration time in Unix epoch seconds. |
iat | number | Optional | Token creation time in Unix epoch seconds. |
email | string | Optional | The customer’s verified email address. |
name | string | Optional | The customer’s full name to be displayed in the agent Inbox. |
phone | string | Optional | The customer’s phone number in E.164 format. |
attrs | object | Optional | Additional custom attribute key-value pairs to be stored on the contact profile. |
Token Generation Example (Node.js)
Section titled “Token Generation Example (Node.js)”import jwt from "jsonwebtoken";
export function signWebchatIdentityToken(user) { return jwt.sign( { sub: String(user.id), external_id: String(user.id), email: user.email, name: user.fullName, exp: Math.floor(Date.now() / 1000) + 3600, }, process.env.MAHADATA_WEBCHAT_SECRET, { algorithm: "HS256" } );}