Webchat Integration in Mobile Apps (WebView)
The Mahadata Webchat widget provides a Standalone mode (?standalone=1) that renders the chat window full-screen without a floating launcher button. This mode is designed to be embedded directly inside a WebView component in native and cross-platform mobile apps.
Standalone URL Format
Section titled “Standalone URL Format”Open the Install & API tab on the Webchat widget settings page (/settings/channels/webchat/<widget_id>/install) and copy Share Chat Link:
https://<portal-origin>/<locale>/webchat/frame/<widget_id>?standalone=1Supported optional query parameters:
| Parameter | Description |
|---|---|
standalone=1 | Renders the chat full screen and hides the iframe close button. |
locale | The display language code (id, en, or zh). |
identity | An optional HS256 JWT token to identify a logged-in user from the initial connection. |
JavaScript Bridge Architecture
Section titled “JavaScript Bridge Architecture”When the frame page is loaded inside a WebView, Mahadata provides a two-way communication bridge:
1. From the Mobile App to the WebView (MahadataChatBridge)
Section titled “1. From the Mobile App to the WebView (MahadataChatBridge)”The mobile app can call window.MahadataChatBridge.identify(jwtToken) at any time after the ready event is received to authenticate the user using a HS256 JWT signed on your backend server:
window.MahadataChatBridge.identify("<SITE_JWT_TOKEN>");2. From the WebView to the Mobile App (Events)
Section titled “2. From the WebView to the Mobile App (Events)”The Webchat frame sends JSON events for three main lifecycles:
ready— The frame has finished loading and is ready to receiveidentifycalls.message— A new message was received from an agent or bot.unread— The unread message count changed (for example, while the app is in the background).
Event payload format:
{ "type": "message", "widgetId": "<WIDGET_UUID>", "message": { "id": "<MESSAGE_UUID>", "sender": "agent", "content": { "type": "text", "body": "Halo, ada yang bisa kami bantu?" } }}{ "type": "unread", "widgetId": "<WIDGET_UUID>", "count": 2}Example Implementation per Platform
Section titled “Example Implementation per Platform”Android (Kotlin WebView + addJavascriptInterface)
Section titled “Android (Kotlin WebView + addJavascriptInterface)”Frame automatically calls window.MahadataAndroid.postMessage(jsonString) if the interface object "MahadataAndroid" registered.
import android.annotation.SuppressLintimport android.os.Bundleimport android.webkit.JavascriptInterfaceimport android.webkit.WebViewimport android.webkit.WebViewClientimport androidx.appcompat.app.AppCompatActivityimport org.json.JSONObject
class SupportChatActivity : AppCompatActivity() { private lateinit var webView: WebView
@SuppressLint("SetJavaScriptEnabled") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) webView = WebView(this) setContentView(webView)
webView.settings.javaScriptEnabled = true webView.settings.domStorageEnabled = true
webView.addJavascriptInterface( object { @JavascriptInterface fun postMessage(payloadJson: String) { val event = JSONObject(payloadJson) when (event.optString("type")) { "ready" -> { val jwt = "<SITE_JWT_FROM_YOUR_BACKEND>" runOnUiThread { webView.evaluateJavascript( "window.MahadataChatBridge.identify('$jwt');", null ) } } "unread" -> { val unreadCount = event.optInt("count", 0) // Perbarui badge notifikasi di aplikasi Anda } } } }, "MahadataAndroid")
webView.webViewClient = WebViewClient() webView.loadUrl("https://<PORTAL_ORIGIN>/id/webchat/frame/<WIDGET_ID>?standalone=1") }}iOS (Swift WKWebView + WKScriptMessageHandler)
Section titled “iOS (Swift WKWebView + WKScriptMessageHandler)”Frame sends the event object directly to window.webkit.messageHandlers.mahadata.postMessage(payload).
import UIKitimport WebKit
class SupportChatViewController: UIViewController, WKScriptMessageHandler { private var webView: WKWebView!
override func viewDidLoad() { super.viewDidLoad()
let contentController = WKUserContentController() contentController.add(self, name: "mahadata")
let config = WKWebViewConfiguration() config.userContentController = contentController
webView = WKWebView(frame: view.bounds, configuration: config) webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(webView)
if let url = URL(string: "https://<PORTAL_ORIGIN>/id/webchat/frame/<WIDGET_ID>?standalone=1") { webView.load(URLRequest(url: url)) } }
func userContentController( _ userContentController: WKUserContentController, didReceive message: WKScriptMessage ) { guard message.name == "mahadata", let body = message.body as? [String: Any], let eventType = body["type"] as? String else { return }
if eventType == "ready" { let jwt = "<SITE_JWT_FROM_YOUR_BACKEND>" webView.evaluateJavaScript("window.MahadataChatBridge.identify('\(jwt)');") } }}Flutter (webview_flutter)
Section titled “Flutter (webview_flutter)”For Flutter, you can use JavaScriptChannel named MahadataAndroid (or forward to ReactNativeWebView):
import 'dart:convert';import 'package:flutter/material.dart';import 'package:webview_flutter/webview_flutter.dart';
class SupportChatScreen extends StatefulWidget { const SupportChatScreen({super.key});
@override State<SupportChatScreen> createState() => _SupportChatScreenState();}
class _SupportChatScreenState extends State<SupportChatScreen> { late final WebViewController _controller;
@override void initState() { super.initState(); _controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..addJavaScriptChannel( 'MahadataAndroid', onMessageReceived: (JavaScriptMessage msg) { final data = jsonDecode(msg.message) as Map<String, dynamic>; if (data['type'] == 'ready') { const jwt = '<SITE_JWT_FROM_YOUR_BACKEND>'; _controller.runJavaScript( "window.MahadataChatBridge.identify('$jwt');", ); } }, ) ..loadRequest( Uri.parse('https://<PORTAL_ORIGIN>/id/webchat/frame/<WIDGET_ID>?standalone=1'), ); }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Bantuan Pelanggan')), body: WebViewWidget(controller: _controller), ); }}React Native (react-native-webview)
Section titled “React Native (react-native-webview)”Frame automatically detects window.ReactNativeWebView.postMessage(jsonString) and forwards the entire event ready, message, and unread.
import React, { useRef } from 'react';import { WebView, type WebViewMessageEvent } from 'react-native-webview';
export function SupportChatWebView({ jwtToken }: { jwtToken: string }) { const webViewRef = useRef<WebView>(null);
const handleMessage = (event: WebViewMessageEvent) => { try { const payload = JSON.parse(event.nativeEvent.data); if (payload.type === 'ready' && jwtToken) { const js = `window.MahadataChatBridge.identify(${JSON.stringify(jwtToken)}); true;`; webViewRef.current?.injectJavaScript(js); } } catch { // Abaikan pesan non-JSON } };
return ( <WebView ref={webViewRef} source={{ uri: 'https://<PORTAL_ORIGIN>/id/webchat/frame/<WIDGET_ID>?standalone=1', }} onMessage={handleMessage} javaScriptEnabled domStorageEnabled /> );}