Native Android WebView Integration Guide

This guide explains how to embed the Talkdesk Chat Widget JS SDK in a native Android app using WebView.

The recommended integration uses a small HTML bridge page that you host on your own domain over HTTPS. The native app loads that bridge page in a WebView, injects the Talkdesk configuration, and receives chat lifecycle events through the Android JavaScript bridge. You do not need to write the bridge page: use the one included in the sample ZIP (bridge/android-playground.html) and deploy it unchanged.

Download Sample Code

Download the native Android example and bridge HTML used by this guide.

Download ZIP

Before You Start: Important Notes

What You Will Build

Integration Architecture
Customer Android App
Kotlin WebView Host
  • Create WebView
  • Inject config via JavaScript
  • Receive SDK events
HTML Bridge Page
  • Load SDK from CDN
  • Call initTalkdeskChat(config)
  • Send events to native

The native app is responsible for:

The bridge page is responsible for:

Requirements

Load the SDK and bridge page over HTTPS in release builds. For local development, debug builds may load the bridge page over HTTP. See Step 1

Configure the Touchpoint in Talkdesk Admin

Before you test the app, check these settings for the chat touchpoint in Talkdesk Admin (Admin > Channels > Chat > Touchpoints > [your touchpoint]):

If the chat does not start after the bridge page loads (the app receives error with Failed to initialize TalkdeskChatSDK), check the touchpoint ID, the region and these settings first. A touchpoint that exists in a different environment than the SDK script is a common cause.

Bridge page and conversation persistence

The bridge page loads the chat widget in an iframe served from the Talkdesk SDK site (talkdeskchatsdk.talkdeskapp.com). The conversation can be restored when the user reopens the chat, including after the app is killed and relaunched.

To retain the conversation, set webView.settings.domStorageEnabled = true, turn Clear chat history off for the touchpoint in Talkdesk Admin, and do not clear WebView storage when minimizing or destroying the chat.

We verified the conversation restoration after the app was killed and relaunched using Android 14, 15 and 16 emulators in Android Studio. It is recommended to perform test restoration on the Android devices and WebView versions you support.

The bridge page source is included in the ZIP (bridge/android-playground.html). If you self-host it, keep it small and trusted, and serve it only over HTTPS.

Step 1: Configure the Android Manifest

Required configuration in app/src/main/AndroidManifest.xml:

The sample's main manifest also disables cleartext HTTP traffic, so release builds use HTTPS:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
  <uses-permission android:name="android.permission.INTERNET" />
  <application
      android:theme="@style/AppTheme"
      android:usesCleartextTraffic="false">
      <activity
          android:name=".MainActivity"
          android:exported="true"
          android:windowSoftInputMode="adjustResize">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
      </activity>
  </application>
</manifest>
    

Optional: local HTTP development. If your local bridge page is served over HTTP, add the following override in app/src/debug/AndroidManifest.xml. It permits cleartext traffic only in debug builds. If all your resources use HTTPS, this override is unnecessary.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
    <!-- HTTP is for a local development server only. Release builds remain HTTPS-only. -->
    <application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic" />
</manifest>
      

In the sample's debug build, enable Local development server and set Local host to the development computer's address. The sample loads the bridge page from http://<localDevHost>:5555/android-playground.html; it continues to load the SDK script from the hosted HTTPS URL.

Before starting the server, check that port 5555 is free; an Android Studio emulator may use it. On macOS or Linux, run lsof -nP -iTCP:5555 -sTCP:LISTEN.

Step 2: Create the Kotlin Configuration

The bridge page validates incoming configurations to prevent invalid app values from disrupting the chat.

Example configuration using JSONObject, as in the Android sample's MainActivity:

val bridgeUrl = "https://YOUR_HOST/android-playground.html"
val config = JSONObject()
    .put("touchpointId", "YOUR_TOUCHPOINT_ID")
    .put("region", "td-us-1")
    .put("scriptURL", "https://talkdeskchatsdk.talkdeskapp.com/v2/talkdeskchatsdk.js")
    .put("enableEmoji", true)
    .put("enableAttachments", true)
    .put("enableSoundNotification", true)
    .put("enableUserInput", true)
    .put("enableChatHeader", true)
    .put("enableValidation", true)
    .put("enableResponsiveLayout", true)
    .put("debug", false)

// Leave languageCode out for Default, or select an explicit language.
config.put("languageCode", "en-US")

Step 3: Create the WebView Manager

The manager owns the WebView, loads the bridge page, injects the config, receives JavaScript events, and cleans up when chat closes.

The following snippets are excerpts from the included ChatWebViewManager and MainActivity. Create the WebView with JavaScript and DOM storage enabled. Keep file access and mixed content disabled:

val trusted = runCatching { BridgeLocation.parse(bridgeUrl, BuildConfig.DEBUG) }.getOrElse {
    fail(it.message ?: "Invalid bridge URL")
    return
}
pageState.reset()
pageState.requestOpen()
onState(true, false)
// Debug inspection is disabled in release builds.
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG)
val view = WebView(activity)
webView = view
launchSettings = settings
view.setBackgroundColor(Color.WHITE)
view.alpha = 0f // Keep a measured viewport during SDK initialization.
view.settings.apply {
    javaScriptEnabled = true
    domStorageEnabled = true
    allowFileAccess = false
    allowContentAccess = true // Content URIs from the system document picker.
    mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
    javaScriptCanOpenWindowsAutomatically = false
    setSupportMultipleWindows(true)
}
CookieManager.getInstance().setAcceptThirdPartyCookies(view, false)

Register the origin-restricted listener and the WebView clients from the following steps before loading the trusted page. The complete manager mounts the view invisibly, starts a 45-second initialization timeout, and calls view.loadUrl(trusted.url).

Keep ChatPageState.kt and the bundled assets with the manager. On WebViews supporting DOCUMENT_START_SCRIPT, the compatibility scripts preserve header-menu behavior and pending attachment selections, including with the hosted SDK. They run only on the allowed bridge and SDK origins; the native message listener remains restricted to the bridge's main frame.

Step 4: Inject SDK Config After the Bridge Page Loads

Inject the config after the bridge page finishes loading. Check that the callback belongs to the current WebView and that the page origin matches the bridge page you loaded. The manager keeps SDK readiness in ChatPageState, separately from the user's open or minimize choice:

private val pageState = ChatPageState()
private val ready: Boolean get() = pageState.ready

A reload creates a new JavaScript document even when the native WebView and URL stay the same. Reset that document's initialization state in onPageStarted, then inject once for the new document in onPageFinished. Keep the current native screen and the open or minimize choice across the reload:

At the start of launch, capture val launchConfig = JSONObject(config.toString()). Build a fresh initialization config for each document so queued context never changes the caller's config or the settings used to decide whether to reuse the WebView.

override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
    if (view !== webView || !trusted.matchesOrigin(url)) return
    // A reload creates a fresh JS realm, even when its URL and native WebView have not changed.
    pageState.pageStarted()
    clearTranscript()
    finishFilePicker(null)
    // Retain the current native screen during a real navigation, rather than flashing configuration.
    onState(true, visible)
    handler.removeCallbacks(loadTimeout)
    handler.postDelayed(loadTimeout, 45000)
}

override fun onPageFinished(view: WebView, url: String) {
    if (view !== webView || !trusted.matchesOrigin(url) || !pageState.beginInitialization()) return
    onEvent("bridgePageLoaded", null)
    // Each document starts from the launch config; clearContext must not leave merged fields behind.
    val initializationConfig = JSONObject(launchConfig.toString())
    if (savedContext.length() > 0) {
        initializationConfig.put("context", mergedContext(initializationConfig.optJSONObject("context")))
    }
    evaluate("window.initTalkdeskChat($initializationConfig)")
}

JSONObject.toString() supplies the JSON value passed to JavaScript. Never concatenate individual customer strings into a script. The bridge exposes window.initTalkdeskChat(config) and its alias window.initSDK(config); initialization is idempotent.

If you serve the bridge page from a development server, make sure it does not reload the page when the app resumes, because a reload starts a new document and the SDK must be initialized again.

Step 5: Receive SDK Events From JavaScript

Compare the message origin with the bridge page you loaded and accept messages only from the main frame. On Android, register TalkdeskNative for the bridge origin using WebViewCompat.addWebMessageListener:

if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
    WebViewCompat.addWebMessageListener(view, "TalkdeskNative", setOf(trusted.origin)) {
        sender, message, sourceOrigin, isMainFrame, _ ->
        if (sender !== webView || !isMainFrame || !trusted.matchesOrigin(sourceOrigin.toString()) ||
            !trusted.matchesOrigin(sender.url.orEmpty())) return@addWebMessageListener
        if (message.type != WebMessageCompat.TYPE_STRING) return@addWebMessageListener
        val data = message.data ?: return@addWebMessageListener
        if (data.length > 16384) return@addWebMessageListener
        val event = runCatching { JSONObject(data) }.getOrNull() ?: return@addWebMessageListener
        if (event.optString("type") == "transcriptData") {
            receiveTranscript(event)
            return@addWebMessageListener
        }
        handleEvent(event)
    }
} else {
    fail("Update Android System WebView or Chrome to use the secure chat bridge.")
    return
}

The bridge sends JSON strings such as:

window.TalkdeskNative.postMessage(JSON.stringify({
  type: 'sdkReady',
  payload: null,
  timestamp: new Date().toISOString()
}))

The onCloseWebchat handler calls minimize() to dispose of the view; the Android Back button uses this same method. See below for details on the optional keep-alive mode.

private fun handleEvent(event: JSONObject) {
    val type = event.optString("type")
    if (type !in setOf("sdkReady", "onOpenWebchat", "onCloseWebchat", "onConversationStart",
            "onConversationEnded", "onConversationClear", "error", "pageError", "contextUpdated")) return
    if (type == "error") dispose()
    onEvent(type, event.optJSONObject("payload")?.toString())
    when (type) {
        "sdkReady" -> {
            if (!pageState.sdkReady()) return
            handler.removeCallbacks(loadTimeout)
            if (pageState.openRequested) {
                show()
                evaluate("window.openTalkdeskChat()")
            } else {
                onState(false, false)
            }
        }
        "onCloseWebchat" -> minimize()
        "onConversationEnded", "onConversationClear" -> cancelAttachmentSelection()
    }
}

The bridge page sends error only for fatal problems: an invalid configuration, or the SDK failing to load or initialize. Tear the WebView down or reload it on error. Non-fatal runtime errors in the page are sent as pageError. Treat pageError as informational and do not close the chat for it. Ignore event types your app does not handle.

On the initial launch, keep the chat container invisible until sdkReady. The WebView can be mounted while the bridge page loads. During a later page reload, preserve the current visibility as described in Step 4.

Minimize and Reopen the Chat

When the user minimizes or closes the chat, the bridge page sends onCloseWebchat. We recommend destroying the WebView at that point, as in Step 5, and creating a new one the next time chat is launched. The chat can restore the conversation from browser storage, so the user can continue the same conversation.

For this to work:

Use the included manager's destruction setting for the recommended integration:

manager.destroyOnMinimize = true
manager.launch(bridgeUrl, config)

With that setting, the existing minimize() method dismisses the keyboard and calls dispose(). The next launch creates a new WebView and initializes the SDK again:

fun minimize(): Boolean {
    if (!visible && !pageState.openRequested) return false
    pageState.minimize()
    cancelAttachmentSelection()
    webView?.let { view ->
        (activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
            .hideSoftInputFromWindow(view.windowToken, 0)
        view.clearFocus()
        view.alpha = 0f
    }
    visible = false
    if (destroyOnMinimize) dispose() else onState(false, false)
    return true
}

Destroying the WebView also frees its memory while the chat is closed. If you prefer to keep it, or Clear chat history is on for your touchpoint, set manager.destroyOnMinimize = false. The manager hides the WebView instead of destroying it and shows it again on the next launch, calling window.openTalkdeskChat() without loading the bridge page again. Whichever you choose, drop the WebView after an error event.

Returning from Home, Recents or another app resumes the same WebView in place. Request layout and redraw for visible chat; do not reload the bridge, initialize the SDK again or call webchat.open() again. An already-visible chat stays visible, and a minimized chat stays hidden:

fun pause() {
    filePickerState.pause()
    webView?.onPause()
    CookieManager.getInstance().flush()
}

fun resume() {
    webView?.onResume()
    filePickerState.resume()
    // Activity results can arrive before onResume; deliver on the next UI loop.
    handler.post { filePickerState.deliver() }
    if (ready && visible) {
        // Never depend on a JS/compositor callback to make a resumed chat visible.
        webView?.let { view ->
            view.alpha = 1f
            view.requestLayout()
            view.invalidate()
        }
    }
}

If Android terminates the renderer, dispose the unusable view and let the next launch create a new one. Do not keep a blank overlay on screen. See Step 9.

Set Context From the Native App

Your app can pass context (key and value pairs such as a customer id or the current app screen) to the chat widget. Context values must be strings. Numbers and booleans are converted to strings, null is skipped, and objects and arrays are ignored.

To set context before the chat starts, pass it in the configuration, under context. It goes to the bridge page with the rest of the configuration:

config.put("context", JSONObject()
    .put("customerId", "CUSTOMER_ID")
    .put("screen", "orders"))
manager.launch(bridgeUrl, config)

To set or update it at any time, call setContext. Calls are merged with earlier context. The manager keeps the context for its lifetime, so it is sent again every time a new WebView is created (for example after the user minimizes the chat and the WebView is destroyed). A call made before the bridge page has loaded, or before the chat is launched, is sent with the configuration. Call clearContext() to forget it:

manager.setContext(JSONObject().put("screen", "order-details"))

// Forget the queued native copy. This does not erase context already in a running SDK.
manager.clearContext()

In the sample, the manager belongs to the Activity. If Android recreates that Activity, supply context again from your app state. It is not saved to preferences. clearContext() clears the manager's saved copy; it does not remove context already sent to the running SDK or supplied in the launch config.

The bridge page sends contextUpdated with the key names once the context is applied. Values are never sent back to the app. Null values are skipped silently; unsupported context entries are reported as a non-fatal pageError and never close the chat.

Context can contain personal data. Send only what the chat flow needs, and do not log context values in your app.

If you maintain your own bridge page, expose a function that calls webchat.setContextParam(context) with string values, and keep calls made before the SDK is created until it is.

User-facing external links should leave the chat WebView and open through Android.

This includes:

Main-frame pages on the bridge origin stay in the WebView, and SDK subframes load normally. Other main-frame destinations are handed to openExternal. New-window requests are accepted only when isUserGesture is true.

override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
    val url = request.url
    val scheme = url.scheme?.lowercase()
    if (scheme in setOf("tel", "mailto", "sms", "geo")) {
        openExternal(url)
        return true
    }
    // Let SDK subframes load their own pages; they never receive the native bridge.
    if (!request.isForMainFrame) return false
    if (trusted.matchesOrigin(url.toString())) return false
    openExternal(url)
    return true
}

Allow only known schemes when launching an external Activity. Handle a missing application without destroying chat:

private fun openExternal(url: Uri) {
    if (url.scheme?.lowercase() !in setOf("https", "http", "tel", "mailto", "sms", "geo")) {
        onEvent("pageError", "Unsupported link scheme")
        return
    }
    try {
        activity.startActivity(Intent(Intent.ACTION_VIEW, url).addCategory(Intent.CATEGORY_BROWSABLE))
    } catch (_: ActivityNotFoundException) {
        onEvent("pageError", "No app can open this link")
    }
}

For new windows, the complete WebChromeClient.onCreateWindow creates a short-lived WebView without the native bridge, routes its destination to an external app, and destroys it. Keep that handler alongside the attachment callback in the same WebChromeClient. Untrusted main-frame navigation must never inherit TalkdeskNative.

override fun onCreateWindow(view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: android.os.Message): Boolean {
    if (!isUserGesture || view !== webView) return false
    // A short-lived WebView intercepts target=_blank and window.open without a native bridge.
    val popup = WebView(activity)
    popups.add(popup)
    popup.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            openExternal(request.url)
            closePopup(view)
            return true
        }
    }
    val transport = resultMsg.obj as WebView.WebViewTransport
    transport.webView = popup
    resultMsg.sendToTarget()
    handler.postDelayed({ closePopup(popup) }, 5000)
    return true
}

Step 7: Handle Attachment Selection

Handle file selection only when attachments are enabled. The sample uses the Android system file picker for existing documents and photos.

Register the Activity result callback before launch:

private val filePicker = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    pickerPending = false
    // The manager holds selected URIs until onResume has restored the existing WebView.
    manager.finishFilePicker(WebChromeClient.FileChooserParams.parseResult(result.resultCode, result.data))
}

The manager handles supported file-selection modes only while attachments are enabled and chat is ready and visible. The Activity launches the picker and returns its result:

override fun onShowFileChooser(
    view: WebView,
    callback: ValueCallback<Array<Uri>>,
    params: FileChooserParams
): Boolean {
    if (view !== webView || !ready || !visible || !launchConfig.optBoolean("enableAttachments", true) ||
        params.mode !in setOf(FileChooserParams.MODE_OPEN, FileChooserParams.MODE_OPEN_MULTIPLE)) return false
    cancelAttachmentSelection()
    filePickerState.begin { callback.onReceiveValue(it) }
    try {
        launchFilePicker(params.createIntent().apply { addCategory(Intent.CATEGORY_OPENABLE) })
    } catch (_: ActivityNotFoundException) {
        finishFilePicker(null)
        onEvent("pageError", "No system file picker is available")
    }
    return true
}

Complete each file chooser callback exactly once. Return null if the request is cancelled or replaced, the chat is minimized, or the WebView is disposed. Accept only content: URIs from the picker; reject file: URIs:

private val filePickerState = FilePickerState<Array<Uri>>()

fun finishFilePicker(uris: Array<Uri>?) {
    // Accept only user-granted provider URIs, never file:// paths into app-private storage.
    val safe = uris?.filter { it.scheme == "content" }?.toTypedArray()?.takeIf { it.isNotEmpty() }
    filePickerState.finish(safe)
    if (safe != null) handler.post { filePickerState.deliver() }
}

private fun cancelAttachmentSelection() {
    finishFilePicker(null)
    // Also cancel a selection already held inside a reconnecting SDK frame.
    evaluate("window.cancelTalkdeskAttachmentSelection && window.cancelTalkdeskAttachmentSelection()")
}

Keep the pickerPending guard from the downloaded MainActivity so two pickers cannot launch at the same time. If no picker is available, report a recoverable pageError and keep chat usable. Keep FilePickerState.kt with the manager: cancellation completes immediately, while selected files wait for the existing WebView to resume. Direct camera capture would require a separate camera launch, output URI and result-handling flow.

Preserve Attachments During Reconnection

Keep FilePickerState.kt and assets/webview-attachment-compat.js with the manager. Selected URIs wait until the existing WebView resumes. On WebViews supporting DOCUMENT_START_SCRIPT, the helper uses MutationObserver to watch disabled / aria-disabled and listens for visibilitychange. When reconnection re-enables the attachment button and the page is visible, resumeSelection() replays the original input's change event once. The SDK's existing attachment handler then sends the retained file. There is no polling or fixed timeout; no reload or SDK reinitialization is needed.

Recovery code inside resumeSelection(), after validating the original input and selection:

if (unavailable(button)) return
clearPending(false)
var change = document.createEvent('Event')
change.initEvent('change', true, false)
input.dispatchEvent(change) // SDK attachment onChange → sendMessage

This continues a pending file selection; it does not retry an upload that has already failed. Cancelled or superseded selections, replaced inputs and page navigation release the pending file and temporary listeners. Keep the manager's origin-restricted script injection and cancelAttachmentSelection() calls so minimizing, ending or clearing the conversation also cancels a retained selection.

Step 8: Handle Transcript Download

Android supports transcript download through the system save picker. Enable Transcript download for the touchpoint in Talkdesk Admin. When the user chooses Download transcript, the SDK generates a temporary blob: URL and clicks an <a download> link.

Keep TranscriptTransfer.kt, TranscriptSaveViewModel.kt and assets/download-transcript.js from the downloaded project alongside ChatWebViewManager. These handle the transfer from JavaScript to Kotlin and saving the file.

Transfer the Transcript to Native Code

Register a DownloadListener before loading the bridge. The manager checks that chat is ready and visible, the current page matches the trusted bridge origin, and the blob belongs to that origin:

view.setDownloadListener { url, _, disposition, _, _ ->
    if (view !== webView || !ready || !visible || !trusted.matchesOrigin(view.url.orEmpty())) {
        return@setDownloadListener
    }
    if (url.startsWith("blob:") && trusted.matchesOrigin(url.removePrefix("blob:"))) {
        startTranscript(url, disposition)
    } else if (url.startsWith("https://") || (BuildConfig.DEBUG && url.startsWith("http://"))) {
        openExternal(Uri.parse(url))
    } else {
        onEvent("pageError", "This download is not supported in the Android demo")
    }
}

The included startTranscript creates a transfer ID and runs assets/download-transcript.js in the trusted bridge page to read the blob. The script sends start, ordered Base64 chunk messages and end through TalkdeskNative.postMessage with type transcriptData. The origin-restricted listener from Step 5 routes these messages to receiveTranscript before SDK event logging.

The manager validates the transfer ID, and TranscriptTransfer checks chunk order and byte count. A complete transfer produces a TranscriptFile and invokes onTranscriptReady. The sample accepts one transfer at a time, limits each file to 5 MiB, rejects empty or incomplete files and requires each transfer to finish within 30 seconds. Never include transcript contents in the event log.

Save the Transcript With the System Picker

In MainActivity, keep the pending file in TranscriptSaveViewModel and register ActivityResultContracts.CreateDocument("text/plain") before launching the picker:

private val transcriptSave by lazy { ViewModelProvider(this)[TranscriptSaveViewModel::class.java] }

private val saveTranscript = registerForActivityResult(ActivityResultContracts.CreateDocument("text/plain")) { uri ->
    transcriptSave.finish(uri, applicationContext.contentResolver)
}

private fun offerTranscriptSave(file: TranscriptFile) {
    if (!transcriptSave.offer(file)) {
        recordEvent("pageError", "Finish the current transcript save before downloading another")
        return
    }
    try {
        saveTranscript.launch(file.name)
    } catch (_: android.content.ActivityNotFoundException) {
        transcriptSave.finish(null, applicationContext.contentResolver)
        recordEvent("pageError", "No system file saver is available")
    }
}

Pass ::offerTranscriptSave as the manager's onTranscriptReady callback, as shown in Step 10. The picker lets the user choose a filename and destination. The filename defaults to transcript.txt when WebView does not supply one. The system grants access to the selected content: URI; no storage permission is required.

TranscriptSaveViewModel.finish writes the bytes through ContentResolver.openOutputStream on a background thread. Observe its result in onCreate to report success, cancellation or a recoverable save error. Clear each displayed result so Activity recreation does not show it again:

transcriptSave.result.observe(this) { result ->
    result ?: return@observe
    recordEvent(result.type, result.message)
    if (result.type != "transcriptSaveCancelled") {
        Toast.makeText(this, result.message, Toast.LENGTH_LONG).show()
    }
    transcriptSave.clearResult()
}

transcriptSaved is reported only after the bytes have been written and the output stream is closed. Cancelling the picker reports transcriptSaveCancelled and keeps chat open; a write failure reports pageError. The pending file survives Activity recreation while the picker is open. If the app process is killed, download the transcript again.

Step 9: Add Error Handling

A fatal configuration or SDK initialization error releases the WebView and returns the user to the native screen:

private fun fail(message: String) {
    dispose()
    onEvent("error", message)
}

For network and HTTP errors reported by onReceivedError and onReceivedHttpError, fail only the active main frame. TLS errors are handled separately: cancel the request and release the active WebView. Renderer termination also releases the unusable view:

override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
    if (view === webView && request.isForMainFrame) fail("Unable to load chat: ${error.description}")
}

override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, response: WebResourceResponse) {
    if (view === webView && request.isForMainFrame) fail("Bridge page returned HTTP ${response.statusCode}")
}

override fun onReceivedSslError(view: WebView, sslHandler: SslErrorHandler, error: SslError) {
    sslHandler.cancel()
    if (view === webView) fail("Chat connection certificate could not be verified")
}

override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
    if (view === webView) fail("Chat WebView stopped. Open chat again to reconnect.")
    return true
}

The manager times initialization out after 45 seconds. Its dispose() removes the timeout, finishes the file callback, closes temporary windows, removes TalkdeskNative, detaches and destroys the WebView, and resets its native state. Page, message and error handlers check the current view before affecting a later launch. It does not clear browser storage or the manager's saved context.

For production apps, show a friendly native error message, for example:

Chat is currently unavailable. Please try again later.

Avoid showing raw technical errors directly to end users. Keep detailed diagnostics in debug-only Logcat output, without logging customer data.

Step 10: Create the Native WebView Container

Put the native screen and a separate chat container in a FrameLayout. Mount the WebView before initialization, but keep the chat container invisible until sdkReady:

WindowCompat.setDecorFitsSystemWindows(window, false)
val root = FrameLayout(this)
val chatContainer = FrameLayout(this).apply {
    setBackgroundColor(Color.WHITE)
    visibility = View.INVISIBLE
}

// Add the native configuration screen first, then the chat overlay.
root.addView(scroll, FrameLayout.LayoutParams(-1, -1))
root.addView(chatContainer, FrameLayout.LayoutParams(-1, -1))
setContentView(root)

// Access the decor/insets controller only after setContentView.
WindowCompat.getInsetsController(window, root).isAppearanceLightNavigationBars = true

Create ChatWebViewManager with that container, the state and event callbacks, a transcript-save callback and a file-picker launcher. The downloaded MainActivity contains the complete wiring, including offerTranscriptSave and Android Back handling.

manager = ChatWebViewManager(this, chatContainer, { loading, visible ->
    chatVisible = visible
    chatContainer.visibility = if (visible) View.VISIBLE else View.INVISIBLE
    trigger.visibility = if (visible) View.GONE else View.VISIBLE
    trigger.updateState(loading)
    cancel.visibility = if (loading) View.VISIBLE else View.GONE
    status.text = if (loading) "Loading chat…" else "Ready"
}, ::recordEvent, ::offerTranscriptSave) { intent: Intent ->
    if (pickerPending) {
        manager.finishFilePicker(null)
    } else {
        pickerPending = true
        try {
            filePicker.launch(intent)
        } catch (error: android.content.ActivityNotFoundException) {
            pickerPending = false
            throw error
        }
    }
}
// Recommended integration policy, matching the iOS guide.
manager.destroyOnMinimize = true

Step 11: Display the Chat WebView Safely

Use a native container around the WebView.

The container background prevents the native screen from showing behind chat. The WebView should respect system bars, display cutouts and keyboard insets so the chat input is not hidden. The Android sample uses adjustResize with:

ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets ->
    val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout())
    val keyboard = insets.getInsets(WindowInsetsCompat.Type.ime())
    view.setPadding(bars.left, bars.top, bars.right, maxOf(bars.bottom, keyboard.bottom))
    insets
}

The manager state callback controls the container and the floating trigger. On the initial launch, keep the native screen available while loading. During a reload, preserve the manager's reported visibility:

// MainActivity: the onState callback passed to ChatWebViewManager.
{ loading, visible ->
    chatVisible = visible
    chatContainer.visibility = if (visible) View.VISIBLE else View.INVISIBLE
    trigger.visibility = if (visible) View.GONE else View.VISIBLE
    trigger.updateState(loading)
    cancel.visibility = if (loading) View.VISIBLE else View.GONE
    status.text = if (loading) "Loading chat…" else "Ready"
}

Forward Activity lifecycle events to the manager. Its restore implementation is shown in Minimize and Reopen the Chat:

override fun onPause() {
    if (::manager.isInitialized) manager.pause()
    super.onPause()
}

override fun onResume() {
    super.onResume()
    if (::manager.isInitialized) manager.resume()
}

override fun onDestroy() {
    if (::manager.isInitialized) manager.dispose()
    super.onDestroy()
}

Why this layout matters:

Optional: Floating Chat Trigger

The sample app starts the chat from a floating button fixed to a corner of the screen, like the launcher of the web chat widget. It is optional: you can use it, or start the chat from any control in your app.

The button is a ready-made Android view, ChatTriggerButton. Its code and default icon are in the download:

app/src/main/
  java/com/talkdesk/chatwidgetdemo/ChatTriggerButton.kt
  res/drawable-nodpi/chat_trigger_icon.png

Add it to your project

Copy ChatTriggerButton.kt and chat_trigger_icon.png into your Android source and drawable resources.

Use it

Add the button above the configuration view and use the manager callback from Step 11 to hide it while chat is visible:

trigger = ChatTriggerButton(this).apply {
    setOnClickListener {
        manager.destroyOnMinimize = true
        manager.launch(bridgeUrl, config)
    }
}
root.addView(trigger, FrameLayout.LayoutParams(dp(64), dp(64), Gravity.BOTTOM or Gravity.END).apply {
    marginEnd = dp(20)
    bottomMargin = dp(20)
})

updateState(loading) swaps the icon for a white spinner and prevents repeated taps during initialization. The button exposes a native button accessibility role and the label Launch Chat.

Customize it

The Android sample defines its appearance in ChatTriggerButton.kt and placement in MainActivity.kt. Edit those source values to customize it.

Setting Default Where to change it
Position Bottom trailing corner Gravity.BOTTOM or Gravity.END in MainActivity
Horizontal / vertical inset 20dp marginEnd / bottomMargin in MainActivity
Width / height 64dp / 64dp Trigger FrameLayout.LayoutParams in MainActivity
Shape Circle GradientDrawable.OVAL in ChatTriggerButton
Background / foreground #007AFF / white Circle color, icon tint and spinner tint in ChatTriggerButton
Icon / size Bundled template / 28dp chat_trigger_icon.png and icon LayoutParams
Loading spinner 24dp, white Spinner LayoutParams and tint
Shadow 6dp elevation, 3dp translationZ Native elevation settings
Pressed scale 0.92, 120ms setPressed in ChatTriggerButton
Accessibility label Launch Chat contentDescription; loading uses Loading chat

Good to know

Step 12: Test the Integration

Test these cases before shipping:

Common Issues

Issue Likely Cause Fix
Chat never appears sdkReady was not received Check bridge page URL, SDK script URL, touchpointId, and region
Chat does not start, error with Failed to initialize TalkdeskChatSDK Wrong touchpointId or region, a touchpoint from a different environment than the SDK script, or touchpoint settings that do not match Check the touchpoint ID and region, and the settings in Configure the Touchpoint in Talkdesk Admin
Conversation is lost after the app is killed DOM storage is disabled, chat history is session-only, or stored chat data was cleared Keep webView.settings.domStorageEnabled = true, turn Clear chat history off, and do not clear WebView storage. See Bridge page and conversation persistence
Chat input is hidden by system navigation or keyboard WebView does not respect system bar or keyboard insets Apply the system bar, cutout and keyboard insets and adjustResize from Step 11
External links do nothing Navigation or new-window handling is missing, or no compatible Android app is available Handle navigation in WebViewClient and new windows in WebChromeClient.onCreateWindow, open supported URLs with Intent.ACTION_VIEW, and handle ActivityNotFoundException
Attachment upload fails File chooser or Activity result handling is missing Implement onShowFileChooser, register the Activity result launcher, and return selected content URIs or null on cancellation. See Step 7
Image is lost after spending time in the file picker The result arrived while the WebView was paused or the conversation was reconnecting Keep FilePickerState.kt, forward Activity lifecycle callbacks, and include the origin-restricted webview-attachment-compat.js asset. The original input listens for usability changes and delivers the selection once it recovers. See Step 7
Chat closes after a link/download navigation A failed subframe resource or unsupported external link was treated as fatal Limit network/HTTP load-failure handling to the active main frame and treat unsupported external links as non-fatal pageError events. See Step 9
White screen after returning to the app The bridge page was reloaded, the new document was not initialized, or the WebView stayed transparent Initialize each new bridge document as in Step 4. Forward onPause and onResume to the manager. Keep the existing WebView and chat container visible on return; a minimized chat stays hidden. If you serve the bridge from a development server, make sure it never reloads the page on its own. See Minimize and Reopen the Chat
App crashes at startup when configuring system bars Insets controller accessed before the window decor exists Call setContentView before accessing WindowCompat.getInsetsController. See Step 10

Production Checklist