Skip to content

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.

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>:

AttributeExplanation
data-widget-idWebchat widget UUID (required).
data-localeInitial widget language (id, en, or zh).
data-identity-tokenOptional JWT HS256 token to authenticate the visitor immediately on initial load.

MethodDescription
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 clicked
document.getElementById("help-btn")?.addEventListener("click", () => {
window.MahadataChat.open();
});
MethodDescription
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 pertanyaan
window.MahadataChat.setLocale("id");
window.MahadataChat.sendDraft("Halo, saya ingin menanyakan status pesanan #INV-1024");

Use MahadataChat.on(event, handler) to subscribe to widget lifecycle events, and MahadataChat.off(event, handler) to unsubscribe:

Event NamePayloadDescription
readyundefinedTriggered when the chat iframe is ready to communicate.
openundefinedTriggered when the chat window is opened.
closeundefinedTriggered when the chat window is closed.
messageobjectTriggered 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 diperlukan
window.MahadataChat.off("unread", onUnreadChange);

Message Interceptor (beforeSend & beforeDisplay)

Section titled “Message Interceptor (beforeSend & beforeDisplay)”
MethodDescription
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 dikirim
window.MahadataChat.beforeSend((text) => {
return text.replace(/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g, "[REDACTED]");
});
// Contoh: Menyembunyikan pesan sistem internal tertentu
window.MahadataChat.beforeDisplay((msg) => {
if (msg?.content?.body?.startsWith("[INTERNAL]")) {
return null;
}
return msg;
});

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.

ClaimTypeRequiredDescription
sub (or external_id)stringYesUnique customer ID in your system (for example "user_9812").
expnumberYesToken expiration time in Unix epoch seconds.
iatnumberOptionalToken creation time in Unix epoch seconds.
emailstringOptionalThe customer’s verified email address.
namestringOptionalThe customer’s full name to be displayed in the agent Inbox.
phonestringOptionalThe customer’s phone number in E.164 format.
attrsobjectOptionalAdditional custom attribute key-value pairs to be stored on the contact profile.
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" }
);
}