Skip to main content

Embed the Visitor Chat in an App WebView

Open the visitor chat page in a WebView or WKWebView owned by your app without using the Visitor SDK. For a host-owned ArkWeb on HarmonyOS, refer to the bridge, permission, and back-navigation implementation in visitor_oh/twt_visitor_sdk/src/main/ets/pages/VisitorPage.ets in the SDK source repository.

Prefer the Visitor SDK. This guide covers loading the page in your own WebView.


Open the page​

Set url to the URL configured in the console. It must use HTTPS. Append your business parameters as a query string after UTF-8 encoding them. Never put a password, cookie, AppSecret, or long-lived token in a URL.

For an in-app experience, include is_app=1 so the visitor page displays its close button:

<console-configured-URL>?is_app=1&lang=zh-cn&theme=system

Android:

webView.settings.javaScriptEnabled = true
webView.settings.domStorageEnabled = true
webView.loadUrl(buildVisitorUrl())

iOS:

let config = WKWebViewConfiguration()
config.preferences.javaScriptEnabled = true
webView.load(URLRequest(url: visitorURL))

Loading the URL is enough to start chatting. Inject the AppBridge described below when you need a close action, native downloads, native notification sounds, or Android recording permission.


Query parameters​

ParameterRequired?Description
is_appRecommended as 1 in an appDisplays the close button and enables app back handling.
langOptional; page language by defaultUI language: en, zh-cn, zh-tw, ja, ko, de, fr, pt, ru, es, vi, th, id, ms, or tl.
themeOptional; light by defaultlight, dark, or system.
directRequired as 1 for a direct conversationEnables direct-conversation mode; chatid is ignored without it.
chatidRequired for a direct conversationTarget conversation ID. chat_id is also accepted.
sbsRequired when binding a business userUnique user ID in your business system.
sbs_mmRequired when sbs is presentSignature for sbs.
ranstrRequired when a signature is usedRandom string included in the signature.
nameOptionalVisitor name.
nicknameOptionalVisitor nickname.
emailOptionalVisitor email address.
phoneOptionalVisitor phone number.
customer_remarkOptionalCustomer remark.
ext_fk_idOptionalExisting visitor ID used to continue historical conversations.
refererOptionalSource page URL. referer_url is also accepted.
source_titleOptionalSource page title.
new_message_sound_modeOptionalSet to native to let the app play new-message sounds; otherwise the page plays them.

Do not send visitor_id. source=webview has the same effect as is_app=1; use one of them rather than both.


WebView requirements​

  • Enable JavaScript and DOM Storage.
  • Cookies and LocalStorage are persistent by default. Do not clear them unnecessarily, or the visitor identity may be lost.
  • Load HTTPS only. Keep the system ATS/Cleartext settings at their secure defaults.
  • For same-origin microphone and camera capture, declare the corresponding system permissions (Android RECORD_AUDIO/CAMERA; iOS NSMicrophoneUsageDescription/NSCameraUsageDescription; HarmonyOS MICROPHONE/CAMERA in the host HAP's module.json5).
  • Use the WebView file picker for attachments. Each platform requires its own integration (onShowFileSelector on HarmonyOS); see Attachment uploads.
  • Keep same-origin HTTPS navigation in the WebView and open cross-origin HTTPS URLs in the system browser.
  • Set the container and WebView backgrounds to the page palette (#F5F7F9 in light mode / #191919 in dark mode) to avoid a white flash on the first frame or during resizing.
  • On iOS, disable scrollView.bounces, alwaysBounceVertical, and alwaysBounceHorizontal so dragging the fixed viewport does not reveal blank space.
  • Apply keyboard avoidance to the container; see Keyboard and viewport.

Keyboard and viewport​

The visitor page has a fixed 100dvh viewport. It does not reposition itself when the keyboard opens: the container must shrink to keep the input visible.

  • Shrink the container: apply keyboard insets to the container to reduce the WebView height. On Android, apply them to the parent FrameLayout; calling setPadding on the WebView itself does not affect the H5 layout. On ArkWeb, use setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE). On iOS, adjust the WKWebView's bottom constraint.
  • Do not rely on scrolling: on iOS, disable scrollView.bounces, alwaysBounceVertical, and alwaysBounceHorizontal. Dragging the fixed viewport only causes overscroll that reveals blank space.
  • Match the background: set the container and WebView backgrounds to the page palette (#F5F7F9 in light mode / #191919 in dark mode). On iOS, also set isOpaque = false and backgroundColor = .clear to prevent a white flash during resizing or on the first frame.
  • Known tradeoff: resizing recreates the WebKit/Blink rendering surface and may cause a one-frame flash when the keyboard opens. Eliminating it completely requires the H5 page to handle keyboard avoidance with visualViewport while the container keeps its size.

Title bar and back navigation​

When you do not use the SDK, the app draws its own title bar, back button, and close control. The visitor page does not render container UI inside the app.

Title

Listen for WebView title changes and display the title in your navigation bar:

  • Android: WebChromeClient.onReceivedTitle.
  • iOS: observe webView.title with KVO. didFinish alone only captures the initial title; the single-page app changes it again when switching conversations.

Back

When the user presses back with the Android system button, an iOS edge gesture, or a custom back button, ask the page first (see System back). Close the WebView or leave the current page only if the page does not consume the action.

iOS edge gesture

Before adding your own left-edge swipe gesture, set webView.allowsBackForwardNavigationGestures to false. WKWebView's built-in back gesture intercepts touches at the screen edge, preventing the host's UIScreenEdgePanGestureRecognizer from receiving events. The result looks like an unresponsive gesture.

Android safe area

Android enforces edge-to-edge for targetSdk 35+. Place your custom navigation bar below the systemBars() inset by adding padding to the root layout, or the status bar will overlap it.

Attachment uploads (file picker)​

The visitor page selects attachments with <input type="file">. The system does not open a picker for you: Android requires onShowFileChooser, iOS requires runOpenPanelWith, and HarmonyOS requires the Web component's onShowFileSelector callback to return true and open a picker. Missing handlers can silently do nothing when the user taps upload, or return an empty selection.

Android​

private var pendingCallback: ValueCallback<Array<Uri>>? = null
private val REQ_FILE = 1001

webView.webChromeClient = object : WebChromeClient() {
override fun onShowFileChooser(
view: WebView,
filePathCallback: ValueCallback<Array<Uri>>,
params: FileChooserParams,
): Boolean {
// Cancel the previous callback first, or the next tap may not open a picker.
pendingCallback?.onReceiveValue(null)
pendingCallback = filePathCallback
val intent = params.createIntent().addCategory(Intent.CATEGORY_OPENABLE)
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, params.mode == FileChooserParams.MODE_OPEN_MULTIPLE)
return runCatching {
startActivityForResult(intent, REQ_FILE)
true
}.getOrElse {
pendingCallback = null
filePathCallback.onReceiveValue(null)
true
}
}
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode != REQ_FILE) return
val callback = pendingCallback ?: return
pendingCallback = null
if (resultCode != Activity.RESULT_OK) return callback.onReceiveValue(null)
val uris = mutableListOf<Uri>()
data?.data?.let(uris::add) // single selection
data?.clipData?.let { clip -> // multiple selection
for (i in 0 until clip.itemCount) clip.getItemAt(i).uri?.let(uris::add)
}
callback.onReceiveValue(uris.takeIf { it.isNotEmpty() }?.toTypedArray())
}

Key points:

  • Always reuse FileChooserParams.createIntent(). It carries the page's accept value and read permission for the current Activity. A hand-built ACTION_GET_CONTENT intent or third-party gallery may open, but the page cannot read the returned URI and the selection appears empty.
  • Call onReceiveValue exactly once for every onShowFileChooser callback. null means that the user cancelled. If you never call it, the page input remains stuck waiting forever.
  • Read only intent.data and intent.clipData. If a host picker returns a result only in EXTRA_STREAM, first copy the file into the app sandbox and return a FileProvider content:// URI.
  • Never return file://. Hosts commonly disable allowFileAccess, and Android 7+ can throw FileUriExposedException.
  • Return the URI to the same Activity that called startActivityForResult. Read permission is granted to that Activity and is lost if you switch Activities.
  • If the host Activity already handles onActivityResult, choose a request code that does not collide with its existing codes.

iOS​

func webView(_ webView: WKWebView,
runOpenPanelWith parameters: WKOpenPanelParameters,
initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping ([URL]?) -> Void) {
let picker = UIDocumentPickerViewController(
forOpeningContentTypes: [.item], asCopy: true) // copies directly into the sandbox
picker.allowsMultipleSelection = parameters.allowsMultipleSelection
picker.delegate = self
self.openPanelCompletion = completionHandler
present(picker, animated: true)
}

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
defer { openPanelCompletion = nil }
guard let completion = openPanelCompletion else { return }
// Copy URLs outside the security scope into tmp, or WebKit reads 0 bytes.
let copied = urls.compactMap(copyToTemporaryDirectory)
completion(copied.isEmpty ? nil : copied)
}

func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
openPanelCompletion?(nil)
openPanelCompletion = nil
}

Key points:

  • Without runOpenPanelWith, there is no file picker. Declaring WKUIDelegate is not enough; the method must be implemented.
  • Call completion exactly once, passing nil on cancellation.
  • Files from iCloud or the Files app are security-scoped. If you do not call startAccessingSecurityScopedResource() or copy into NSTemporaryDirectory(), WebKit cannot read the URL and uploads contain 0 bytes. asCopy: true is the simplest option.
  • A photo picker (PHPickerViewController) or camera also works, but those APIs return images or asset identifiers rather than file URLs. Write a temporary file first; do not pass a UIImage or asset identifier to completion.

HarmonyOS​

Sample methods: VisitorView.onShowFileSelector() → pickFromAlbum() / pickDocuments() → stageForWeb() → finishPicked(). See visitor_oh/twt_visitor_sdk/src/main/ets/pages/VisitorPage.ets.

Web({ src: url, controller: this.controller })
.onShowFileSelector((event: OnShowFileSelectorEvent) => {
this.onShowFileSelector(event);
return true; // The host opens the picker; false falls back to ArkWeb's default implementation.
})

private onShowFileSelector(event: OnShowFileSelectorEvent): void {
const accept = event.fileSelector.getAcceptType();
const multiple = event.fileSelector.getMode() === FileSelectorMode.FileOpenMultipleMode;
// Use the album for images/videos: the document picker cannot access the gallery,
// and the page may reject HEIC originals.
const wantsMedia = accept.some((t: string) => t.startsWith('image/') || t.startsWith('video/'));
if (wantsMedia) {
this.pickFromAlbum(event.result, accept, multiple);
} else {
this.pickDocuments(event.result, multiple);
}
}

Key points:

  • Return true. With false, ArkWeb uses its own picker and returns its own temporary paths to the page; the host cannot access those files.
  • Call event.result.handleFileList(uris) exactly once. Return [] on cancellation; omitting the callback leaves the page input waiting indefinitely.
  • Album URIs such as file://media/Photo/... have one-time authorization. Copy the file into the sandbox with fs.copyFile, then use fileUri.getUriFromPath to create a URI that the WebView can read.
  • If the page's accept list does not include heic/heif, convert album originals to JPEG with image.createImageSource and packing before returning them, or the selection will be empty.
  • Copy document-picker URIs such as file://docs/... into the sandbox too; do not pass a docs URI directly to the page.
  • Declare album and camera permissions in the host HAP's module.json5. Declarations in the HAR alone are insufficient.

Notes for all platforms​

  • HEIC: If the visitor page's accept list does not include heic or heif, iOS originals and some Android galleries can return a valid HEIC URI that the page silently drops. Convert it to JPEG (or save a JPEG copy) before returning it when original photos must be supported.
  • File size: The SDK does not compress files. The page must handle very large files; the host may check a size limit before returning a URI and show a message.

When the selected file is empty​

SymptomCommon cause
Tapping upload does nothingiOS does not implement runOpenPanelWith; Android did not resolve the previous onReceiveValue callback; HarmonyOS did not return true from onShowFileSelector or call handleFileList.
The file input is still emptyCancellation or empty data was returned as null; the URI was only in EXTRA_STREAM.
A filename appears but the upload is 0 bytesAn Android file:// URI was returned; read permission belongs to another Activity; or an iOS security-scoped URL was not copied.
A selected photo does not enter the listHEIC was filtered by the page's accept value.

AppBridge​

The page calls the app with window.AppBridge.call(method, params, callback). Inject the following script before each page loads (prefer atDocumentStart; do not wait for onPageFinished):

(function () {
window.__TWT_VISITOR_BRIDGE_CONFIG__ = { newMessageSoundMode: 'web' };
window.AppBridge = {
_callbacks: {},
call: function (method, params, callback) {
var id = callback ? 'cb_' + Date.now() + '_' + Math.random().toString(16).slice(2) : null;
if (callback) this._callbacks[id] = callback;
var msg = JSON.stringify({ method: method, params: params || {}, callback: id });
if (window.AppBridgeChannel_native) {
window.AppBridgeChannel_native.postMessage(msg);
} else if (window.webkit && window.webkit.messageHandlers.AppBridgeChannel) {
window.webkit.messageHandlers.AppBridgeChannel.postMessage(msg);
}
return Promise.resolve({ status: 'sent', callbackId: id });
},
invokeCallback: function (id, result) {
var cb = this._callbacks[id];
if (cb) { cb(result); delete this._callbacks[id]; }
}
};
})();

On Android, register a JavascriptInterface named AppBridgeChannel_native with a postMessage method. On iOS, register a WKScriptMessageHandler named AppBridgeChannel. On HarmonyOS, use javaScriptProxy to register the corresponding channel. See VisitorView's proxy and bridgeScript implementations.

Messages use this JSON shape:

{ "method": "...", "params": {}, "callback": "cb_..." }

Methods called by the page​

MethodWhen it is calledWhat the app should do
closeThe user taps the page close buttonClose the WebView or leave the current page.
downloadThe user saves an image, video, or fileDownload params.url, then report the result as described below.
new_messageA new message arrives and native sound is enabledPlay the notification sound. params may contain messageId or chatId.
android_recording_permissionAndroid recording startsRequest microphone permission and return { code: 1, data: { permission: true/false } }.
visitor_back_resultThe page responds to a back requestSee System back.

Without the bridge, the close button has no effect, downloads use the browser, and the page plays its own notification sounds.

Report download results​

The download parameters are:

FieldDescription
urlFile URL.
typeimage, video, or another file type.
fileNameSuggested file name.
mimeTypeMIME type.
requestIdID of this download request.

When the request includes a callback, invoke it after the download finishes:

window.AppBridge.invokeCallback(callbackId, {
code: 1,
data: { requestId: '...', status: 'completed' }
})

status is completed, failed, or cancelled. Use code: 0 for a failed download.

ArkWeb on HarmonyOS starts downloads automatically. Intercept WebDownloadDelegate.onDownloadStart and call item.cancel(), then pass item.getUrl(), getMimeType(), and getSuggestedFileName() to the host. See VisitorView.setupDownloadDelegate(). Without cancellation, the file downloads to ArkWeb's temporary directory and the system shows an unrelated download completion notification.

To let the app play notification sounds, set newMessageSoundMode to 'native' in the injected configuration or add new_message_sound_mode=native to the URL.


System back (optional)​

When the user presses the system back button, ask the page first. It can close a preview or return from a conversation to the list:

window.dispatchEvent(new CustomEvent('twt:visitor-event', {
detail: { type: 'back', payload: {} }
}))

The page reports the result in two places: it sets window.__twtVisitorBackConsumed to true or false and calls visitor_back_result through AppBridge with params.consumed. The host only needs to read one of them. If no response arrives within about 300 ms (350 ms on iOS), treat the action as unconsumed instead of waiting indefinitely.

Android:

webView.evaluateJavascript(
"(function(){window.__twtVisitorBackConsumed=false;" +
"window.dispatchEvent(new CustomEvent('twt:visitor-event',{detail:{type:'back',payload:{}}}));})()",
null,
)
Handler(Looper.getMainLooper()).postDelayed({
webView.evaluateJavascript("!!window.__twtVisitorBackConsumed") { raw ->
if (raw != "true") finish() // Close only if the page did not consume the action.
}
}, 300)

iOS:

let js = "window.__twtVisitorBackConsumed=false;" +
"window.dispatchEvent(new CustomEvent('twt:visitor-event',{detail:{type:'back',payload:{}}}))"
webView.evaluateJavaScript(js) { _, _ in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
webView.evaluateJavaScript("!!window.__twtVisitorBackConsumed") { result, _ in
if (result as? Bool) != true { dismiss(animated: true) }
}
}
}

HarmonyOS (VisitorView.handleBackRequest() in the sample):

this.controller.runJavaScript(
"window.__twtVisitorBackConsumed=false;" +
"window.dispatchEvent(new CustomEvent('twt:visitor-event',{detail:{type:'back',payload:{}}}))",
);
setTimeout(() => {
this.controller.runJavaScript('!!window.__twtVisitorBackConsumed').then((raw: string) => {
if (raw !== 'true') {
this.getUIContext().getRouter().back(); // Close only if the page did not consume the action.
}
});
}, 300);

Connect the custom back button, Android system back button, iOS edge gesture, and HarmonyOS system back (onBackPress) to the same function. On iOS, disable allowsBackForwardNavigationGestures first so the WebView does not intercept the edge gesture.

To change the theme while the page is running (only light or dark):

window.dispatchEvent(new CustomEvent('twt:visitor-event', {
detail: { type: 'themeChanged', payload: { theme: 'dark' } }
}))