Skip to main content

TWT Visitor SDK

Open the visitor chat page inside your app. After the host supplies an HTTPS URL, the SDK loads it in the platform WebView, WKWebView, or ArkWeb and handles navigation, permissions, download status reporting, and site-data cleanup.

If your app owns the WebView and does not use the SDK, see Embed the Visitor Chat in an App WebView.

Current version: 0.0.4

PlatformRequirementIntegration
AndroidminSdk 23Maven Central: io.github.twt-chat:visitor-sdk:0.0.4
iOSiOS 15+SPM: https://github.com/TWT-Chat/twt-visitor-ios.git (tag 0.0.4, product TwtVisitorSDK)
FlutterFlutter ≥ 3.44, Dart ^3.12.0Git: https://github.com/TWT-Chat/visitor_flutter.git (ref 0.0.4)
HarmonyOSHarmonyOS 6.1 (API 23)+ohpm central registry: twt_visitor_sdk@0.0.4; local dependency: visitor_oh/twt_visitor_sdk in the SDK repository

Integration​

Android​

dependencyResolutionManagement {
repositories {
google()
mavenCentral()
}
}

dependencies {
implementation("io.github.twt-chat:visitor-sdk:0.0.4")
}

The SDK includes INTERNET, RECORD_AUDIO, and CAMERA as optional permissions (required=false). On Android 9 and earlier, add WRITE_EXTERNAL_STORAGE yourself when downloading to the public Downloads directory.

iOS​

In Xcode, choose File → Add Package Dependencies and enter:

https://github.com/TWT-Chat/twt-visitor-ios.git

Select Exact Version 0.0.4, choose the TwtVisitorSDK product, and set the deployment target to iOS 15 or newer.

Declare these usage descriptions in Info.plist:

<key>NSMicrophoneUsageDescription</key>
<string>Use the microphone to send voice messages</string>
<key>NSCameraUsageDescription</key>
<string>Use the camera to take and send photos or videos</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Save conversation images</string>
<key>UIFileSharingEnabled</key>
<true/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>

Keep App Transport Security at its default settings. Call public APIs on the main thread.

Flutter​

dependencies:
visitor_flutter:
git:
url: https://github.com/TWT-Chat/visitor_flutter.git
ref: 0.0.4
flutter pub get

The Android project must configure mavenCentral() (see the Android section above). If you use RepositoriesMode.PREFER_SETTINGS, also retain the Flutter Engine repository https://storage.googleapis.com/download.flutter.io. iOS does not need another SPM dependency; use the Info.plist declarations from the iOS section.

HarmonyOS​

The minimum system version is HarmonyOS 6.1 (API 23). Add the package from the ohpm central registry to the entry module's oh-package.json5:

{
"dependencies": {
"twt_visitor_sdk": "0.0.4"
}
}

The registry distributes a bytecode HAR. Keep strictMode.useNormalizedOHMUrl = true in the host project's build-profile.json5 (the DevEco template default). Disabling it causes the build error 00306046 Bytecode HAR [twt_visitor_sdk] not supported when useNormalizedOHMUrl is not true.

For a local dependency, use "twt_visitor_sdk": "file:../twt_visitor_sdk" for the SDK repository's source directory (visitor_oh/twt_visitor_sdk), or run ohpm install ./libs/twt_visitor_sdk-0.0.4.har. The HarmonyOS package uses the Apache-2.0 license; the Android and iOS packages currently use a Proprietary license.

The HAR declares ohos.permission.INTERNET, ohos.permission.MICROPHONE, and ohos.permission.CAMERA. For user-granted permissions, the host HAP must also declare MICROPHONE and CAMERA in its own module.json5; the HAR declarations alone are insufficient. See visitor_oh/entry/src/main/module.json5 in the sample.


Quick start​

An integration needs only three things:

  1. url (required): the URL configured in the console. It must use HTTPS.
  2. Configuration fields: SDK options such as isApp, language, theme, directChatId, and newMessageSoundMode. All have defaults.
  3. query: business parameters for the visitor page. The SDK does not interpret keys; it only UTF-8-encodes them into the URL. Anonymous visitors can omit the map.

Do not build ?a=1&b=2 yourself. Never put a password, cookie, AppSecret, or long-lived token in a URL.

With only url, the SDK produces:

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

The default configuration writes lang=zh-cn and theme=system. To show a close button inside the app, set isApp = true.

Android​

val handle = TwtVisitorSdk.start(
this,
VisitorConfig(url = "<console-configured-URL>"),
)

start validates the configuration first. An empty or non-HTTPS URL throws IllegalArgumentException, which the host must catch with try / catch. After validation, it opens VisitorActivity and returns a VisitorHandle. A non-Activity context automatically receives FLAG_ACTIVITY_NEW_TASK. See Callbacks and events for download and new-message callbacks.

To draw your own title bar, use embed and put the bare WebView in your layout:

val visitorView = TwtVisitorSdk.embed(this, config, listener)
// Put your toolbar (back button + title) at the top, with visitorView below it.

The sample uses a regular page: the system status bar, a custom 56dp toolbar with a back button and the web page title, then the WebView. Android enforces edge-to-edge for targetSdk 35+. Apply padding from WindowInsetsCompat.Type.systemBars() to the root layout (applySystemBarInsets() in the sample), or the status bar will overlap the toolbar.

Forward onBackPressed (visitorView.handleBack(::finish)), onResume / onPause, onDestroy (visitorView.destroySession()), onActivityResult, and onRequestPermissionsResult to the view. See android/sample/.../EmbeddedVisitorActivity.kt for the complete example.

iOS​

Open a separate page containing a full-screen bare WebView:

import TwtVisitorSDK

let config = VisitorConfiguration(
url: URL(string: "<console-configured-URL>")!
)
let handle = try TwtVisitorSDK.present(from: self, configuration: config, delegate: self)

The page is presented as .fullScreen with no system back gesture. The SDK does not draw container UI, handle back navigation, or forward the page's close event. The host must provide a button that calls handle.close() or dismisses the page. The handle is no longer valid after dismissal.

For a title bar and back button, wrap the controller in your own container:

let controller = try TwtVisitorSDK.makeEmbeddedController(configuration: config, delegate: self)
let container = UINavigationController(rootViewController: controller)
// The iOS 26 glass navigation bar samples the WebView background; use an opaque appearance.
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
container.navigationBar.standardAppearance = appearance
container.navigationBar.scrollEdgeAppearance = appearance
controller.navigationItem.leftBarButtonItem = UIBarButtonItem(
image: UIImage(systemName: "chevron.backward"),
primaryAction: UIAction { [weak container] _ in container?.dismiss(animated: true) }
)
present(container, animated: true)

Use visitorTitleChanged(_:) to update controller.navigationItem.title with the web page title.

Flutter​

Build a host-owned page (recommended) with Scaffold and your own AppBar. The WebView occupies only the content area:

import 'package:visitor_flutter/visitor_flutter.dart';

final config = VisitorConfiguration(url: '<console-configured-URL>');

Scaffold(
appBar: AppBar(title: Text(_webTitle ?? 'Customer service')), // _webTitle comes from titleChanged
body: VisitorView(configuration: config),
)

VisitorView must be placed in a parent with a definite size, such as the body of a Scaffold, Expanded, or SizedBox.

A new configuration (URL, query, isApp, language, theme, or directChatId) recreates the platform view and loads the new URL. Changing only newMessageSoundMode does not reload the page. Use VisitorFlutter.setTheme to change the theme at runtime instead of changing the configuration.

To open a separate native page:

final handle = await VisitorFlutter.present(configuration: config);

On Android, this opens the SDK Activity. The SDK handles the system back action by asking the page first and closing only if the page does not consume it. On iOS, this opens a full-screen bare WebView with no system back gesture or SDK-provided close control. Use the host-owned page above so users can exit.

HarmonyOS​

Open a separate page containing a bare WebView, with no title bar. The SDK handles system back navigation:

import { common } from '@kit.AbilityKit';
import { TwtVisitorSDK, VisitorConfig, VisitorHandle } from 'twt_visitor_sdk';

const config = new VisitorConfig();
config.url = '<console-configured-URL>';
config.isApp = true;

const handle: VisitorHandle | null = TwtVisitorSDK.start(
getContext(this) as common.UIAbilityContext,
config,
listener,
);
if (handle === null) {
// Invalid URL or query: the SDK does not open the page.
}

Unlike Android, start returns null for an invalid URL instead of throwing.

For a separate page, import the page file once in the host entry point to register its named route:

import 'twt_visitor_sdk/src/main/ets/pages/VisitorPage';

To draw your own title bar, use embed with VisitorView:

const session = TwtVisitorSDK.embed(config, listener);
// Put your title bar (back button + title) at the top, with VisitorView below it.
VisitorView({ session: session })

The SDK does not draw container UI. Receive the web page title through VisitorBridgeListener.onTitleChanged. Route both custom and system back actions through session.handleBack(() => { ... }). The SDK asks the page first (300 ms), then invokes the callback only if the page did not consume the action and the WebView has no history. See visitor_oh/entry/src/main/ets/pages/EmbeddedPage.ets for a complete example.


Configuration​

The fields are the same on all four platforms. The SDK writes selected fields to the URL and overrides duplicate keys in query.

FieldDefaultIn URL?Description
urlEmpty (required)Base URLConsole-configured URL; HTTPS only. HTTP, file:, javascript:, custom schemes, and user:pass credentials are rejected.
queryEmpty mapAs providedBusiness parameters; see the next section. Do not manually add ?a=1.
isAppfalseWrites is_app=1 when trueIn-app mode; displays the visitor-page close button. false does not write is_app=0.
languagezh-cnAlways writes langen / zh-cn / zh-tw / ja / ko / de / fr / pt / ru / es / vi / th / id / ms / tl
themesystemAlways writes themelight, dark, or system. Runtime setTheme accepts only light or dark.
directChatIdnullWrites direct=1&chatid= when setOpens a conversation directly and removes chat_id.
newMessageSoundModewebGenerally noweb: the page plays the sound; native: the host plays it from the new-message callback. Uses the JS bridge rather than the URL (Flutter Android present() additionally adds new_message_sound_mode).

Write order is: query already present in url → config.query → is_app/lang/theme/direct + chatid. Later values override earlier ones.

Business query parameters​

query is a transparent map. The SDK only encodes and appends it; it does not interpret keys. Anonymous visitors can omit the map. Configure is_app/lang/theme/direct/chatid through the typed fields instead of putting them in query.

To bind a business user:

query = mapOf(
"sbs" to "user-123",
"sbs_mm" to signature,
"ranstr" to randomStr,
"name" to "Alex",
)
ParameterRequired?Description
sbsRequired when binding a userUnique user ID in your business system; the page uses it to identify a logged-in customer.
sbs_mmRequired when sbs is presentSignature for sbs.
ranstrRequired when a signature is usedRandom string included in the signature.
nameOptionalVisitor name, shown in the agent workspace.
nicknameOptionalVisitor nickname.
emailOptionalVisitor email address.
phoneOptionalVisitor phone number.
customer_remarkOptionalCustomer remark submitted with login to the agent side.
ext_fk_idOptionalExisting visitor ID used to continue historical conversations.
refererOptionalSource page URL. referer_url is also accepted and is shown as a source link to agents.
source_titleOptionalSource page title.

Do not send visitor_id or source=android/ios/flutter; the visitor page does not read them. Use isApp=true as the app indicator.


Session APIs​

CapabilityAndroidiOSFlutterHarmonyOS
Open a separate pageTwtVisitorSdk.startTwtVisitorSDK.presentVisitorFlutter.presentTwtVisitorSDK.start
EmbedTwtVisitorSdk.embedmakeEmbeddedControllerVisitorViewTwtVisitorSDK.embed + VisitorView
Change themehandle.setThemehandle.setThemeVisitorFlutter.setTheme / handle.setThemehandle.setTheme
Report a downloadhandle.reportDownloadStatusSameVisitorFlutter.reportDownloadStatushandle.reportDownloadStatus
Closehandle.close()handle.close()Host calls Navigator.pop(); the handle returned by present cannot close the page on iOS, so use a host-owned pagehandle.close() (separate pages only)
Clear site dataTwtVisitorSdk.clearSiteDataTwtVisitorSDK.clearSiteDataVisitorFlutter.clearSiteDataTwtVisitorSDK.clearSiteData

Download statuses are started, completed, failed, or cancelled. requestId must match the request. Optional fields are path, progress, sourceUrl, mimeType, bytes, errorCode, and message. On iOS, a completed Photos asset uses photos://localIdentifier as its path.

Clear results are SUCCESS, INVALID_URL, UNSUPPORTED, IN_USE, or FAILED (Flutter exposes lower camel-case values). IN_USE means a session still holds the host.

On HarmonyOS, clearSiteData clears only the target origin's Web Storage. ArkWeb has no API for deleting cookies by site, and the SDK does not clear cookies globally.

To switch accounts: close every page → wait for destruction to complete → call clearSiteData and wait for success → open the next account.


Callbacks and events​

Callbacks run on the main thread. Deduplicate by requestId or messageId, and mark unfinished downloads as failed when the page is destroyed.

Android — VisitorBridgeListener

  • onDownloadRequested: start the download, then call reportDownloadStatus.
  • onNewMessage: a new message arrived.
  • onBack(): back-button handling; true means the host handled it.
  • onPermissionResult: permission result.
  • onTitleChanged: web page title. The SDK does not draw a title bar; the host displays it if needed.

iOS — VisitorBridgeDelegate (weak reference)

  • visitorDownloadRequested(...)
  • visitorNewMessage() (may be repeated)
  • visitorBack() -> Bool
  • visitorPermissionResult(...)
  • visitorTitleChanged(_:): web page title. The SDK does not draw a title bar; the host displays it if needed.

Flutter — VisitorFlutter.events

Events are not buffered when there is no listener. Start listening when the page opens and cancel the subscription when it is disposed.

late final StreamSubscription<VisitorBridgeEvent> sub;

@override
void initState() {
super.initState();
sub = VisitorFlutter.events.listen((e) {
switch (e.type) {
case 'downloadRequested':
break;
case 'titleChanged': // payload: {'title': ...}
break;
case 'backRequested': // Native back: system back button / iOS edge gesture
unawaited(_handleBack());
break;
case 'webReady':
case 'webLoadFailed':
case 'close':
case 'new_message':
break;
}
});
}

@override
void dispose() {
sub.cancel();
super.dispose();
}

Event names are downloadRequested, webReady, webLoadFailed, close, backRequested, new_message, titleChanged, and theme.

backRequested reports a native back action, such as the Android system back button or iOS edge gesture. It only reports the action and does not close the page. Route it through the same handleBack() check used for system back actions. The example's unawaited function comes from dart:async.

Handle back for an embedded page as follows:

PopScope(
canPop: false,
onPopInvokedWithResult: (_, __) async {
if (!await VisitorFlutter.handleBack()) {
if (context.mounted) Navigator.of(context).pop();
}
},
child: VisitorView(configuration: config),
)

handleBack() == true means the page consumed the back action, for example by returning from a conversation detail to the list. Call VisitorFlutter.reload() after an initial load failure when appropriate.

HarmonyOS — VisitorBridgeListener

  • onDownloadRequested: start the download, then call reportDownloadStatus.
  • onNewMessage: a new message arrived when sound mode is native.
  • onBack(): back-button handling; true means the host handled it.
  • onPermissionResult: permission result.
  • onTitleChanged: web page title. The SDK does not draw a title bar; the host displays it if needed.

HarmonyOS sample methods for back navigation, downloads, and uploads:

ScenarioSample methodsLocation
Separate-page backVisitorPage.onBackPress() → VisitorHandle.handleBack() → VisitorView.handleBackRequest()twt_visitor_sdk/src/main/ets/pages/VisitorPage.ets
Embedded-page backHost onBackPress() / custom back button → session.handleBack(() => ...)entry/src/main/ets/pages/EmbeddedPage.ets
DownloadDemoListener.onDownloadRequested() → DemoDownloadManager.handleDownload() → copyToTarget() → handle.reportDownloadStatus()entry/src/main/ets/service/DemoListener.ets, DemoDownloadManager.ets
UploadVisitorView.onShowFileSelector() → pickFromAlbum() / pickDocuments() → stageForWeb() → finishPicked()twt_visitor_sdk/src/main/ets/pages/VisitorPage.ets
New-message soundDemoListener.onNewMessage() → DemoRingTonePlayer.play() (notification audio stream; falls back to vibration if the resource is missing or playback fails)entry/src/main/ets/service/DemoListener.ets, DemoRingTonePlayer.ets

The SDK handles uploads internally; the host only needs to declare microphone and camera permissions in module.json5. Downloads must be implemented by the host: the SDK passes the URL to it.


Back navigation​

The visitor page is a single-page app. A back action may close an image preview or return from a conversation to the list. Ask the page first: keep the container open if the page consumes the action, and close it otherwise. The SDK forwards and reports events; the host decides whether to close the page.

Entry pointWho handles backHost code
Android TwtVisitorSdk.startBuilt into the SDKNo code needed; intercept onBack() for an exit confirmation
Android TwtVisitorSdk.embedHostvisitorView.handleBack { finish() }
iOS TwtVisitorSDK.present / makeEmbeddedControllerHostCustom back button → handle.close() or dismiss
Flutter VisitorViewHostPopScope(canPop: false) + VisitorFlutter.handleBack()
Flutter VisitorFlutter.presentBuilt in on Android / host on iOSUse a host-owned page on iOS
HarmonyOS TwtVisitorSDK.startBuilt into the SDKNo code needed; intercept onBack() for an exit confirmation
HarmonyOS TwtVisitorSDK.embed + VisitorViewHostsession.handleBack(() => router.back())

Examples: android/sample/.../EmbeddedVisitorActivity.kt, ios/Sample/TwtVisitorSample/MainViewController.swift, and visitor_flutter/example/lib/main.dart.

Android​

Separate pages need no host code: the system back button and system back gesture enter the Activity's back callback → ask the page → close the Activity if the page does not consume the action. To add an exit confirmation, implement onBack() and return true:

override fun onBack(): Boolean {
showExitConfirmDialog()
return true // Intercepted; the SDK will not close the page.
}

For embedded pages, connect the same logic to the host Activity and your custom back button:

override fun onBackPressed() {
visitorView.handleBack { finish() }
}

backButton.setOnClickListener { visitorView.handleBack { finish() } }

The physical back button, system back gesture, and custom back button all use this entry point. handleBack already asks the page internally (300 ms); the host does not need to check again.

iOS​

The native SDK does not handle back navigation or forward the page's close event. The host container provides the back button and left-edge gesture, both calling the same close method:

let visitor = try TwtVisitorSDK.makeEmbeddedController(configuration: config, delegate: self)
visitor.navigationItem.leftBarButtonItem = UIBarButtonItem(
image: UIImage(systemName: "chevron.backward"),
style: .plain,
target: self,
action: #selector(closeVisitor)
)
let container = UINavigationController(rootViewController: visitor)
container.modalPresentationStyle = .fullScreen

// Left-edge back gesture
let edgeBack = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleEdgeBack(_:)))
edgeBack.edges = .left
edgeBack.cancelsTouchesInView = false // Preserve taps and scrolling.
container.view.addGestureRecognizer(edgeBack)
present(container, animated: true)

@objc private func handleEdgeBack(_ gesture: UIScreenEdgePanGestureRecognizer) {
guard gesture.state == .ended else { return }
closeVisitor()
}

@objc private func closeVisitor() { dismiss(animated: true) }
  • The SDK disables the WebView's allowsBackForwardNavigationGestures so it does not intercept the host's edge gesture. Do not enable it again.
  • A full-screen bare page opened with present has no navigation bar or back gesture. The host-provided button is the only exit; the page's close button does not work in the native iOS SDK.
  • Native iOS currently has no public API to ask the page before closing, such as when an image preview or conversation detail is open. The host can only close directly.

Flutter​

PopScope(
canPop: false, // Ask the page before allowing the system to pop.
onPopInvokedWithResult: (didPop, result) {
if (!didPop) unawaited(_handleBack());
},
child: VisitorView(configuration: config),
)

Future<void> _handleBack() async {
if (await VisitorFlutter.handleBack()) return; // Consumed by the page; stay here.
if (mounted) Navigator.of(context).pop();
}

Route all three sources to _handleBack():

SourceHow it reaches the host
AppBar back arrowUses Navigator.maybePop by default; PopScope(canPop: false) intercepts it and invokes the callback
Android physical back button / system back gestureUses the same Flutter back callback
iOS edge gesture or a back action recognized by native codebackRequested event

The in-page close button emits close; the host pops directly. The plugin waits 300 ms for the page (350 ms on iOS) and treats a timeout as unconsumed.

HarmonyOS​

Separate pages need no host code: VisitorPage.onBackPress asks the page first and exits if the action is not consumed. To show a confirmation before closing, return true from listener.onBack.

For embedded pages, connect system back and your custom back button to the same method:

onBackPress(): boolean {
const session = this.session;
if (session === null) {
return false; // Let the system handle back when no session exists, so an error page cannot trap the user.
}
session.handleBack(() => {
this.getUIContext().getRouter().back();
});
return true;
}

For the in-page close button, the SDK forwards the event and exits a separate page. Embedded pages do not forward it; the host provides its own close or back button.

Page-side protocol​

When integrating your own WebView or debugging back navigation, the protocol has three steps:

  1. Dispatch twt:visitor-event with detail.type = 'back'.
  2. Within 300 ms (350 ms on iOS), the page sets window.__twtVisitorBackConsumed and calls visitor_back_result through AppBridge. params.consumed = true means it handled the action. The Flutter plugin also includes requestId.
  3. The host reads window.__twtVisitorBackConsumed or waits for visitor_back_result. Close the container on false or timeout.

For page-side details, see the system back section in Embed the Visitor Chat in an App WebView.


Runtime behavior​

Navigation

Same-origin HTTPS stays inside the container. Cross-origin HTTPS opens in the system browser; other schemes are intercepted.

Storage

Cookies, LocalStorage, and IndexedDB persist by default. Third-party cookies and mixed content are disabled.

Permissions

Only same-origin HTTPS microphone and camera capture reaches a system prompt; cross-origin requests are rejected. Flutter embedded pages on Android allow the microphone but reject the camera. Use a separate page or the native SDK when camera capture is required. On HarmonyOS, only capture requests from the current visitor page origin are allowed. The host HAP must declare microphone and camera permissions itself.

File selection

Uses the system/WebKit file picker and supports single and multiple selection. On HarmonyOS, VisitorView.onShowFileSelector() handles selection: images and videos use the album picker (pickFromAlbum), and documents use the file picker (pickDocuments). stageForWeb() converts originals such as HEIC that the page's accept list does not support to JPEG before returning them to the page.

Downloads

WebView and in-page downloads are sent to the host. The host performs the download and reports the final status. On HarmonyOS, the SDK cancels ArkWeb's built-in download and passes only the URL to the host, so files do not end up in a temporary directory. See VisitorView.setupDownloadDelegate() and DemoDownloadManager.handleDownload().

Back

See Back navigation. Examples: VisitorPage.onBackPress() for separate pages, and EmbeddedPage.onBackPress() → session.handleBack() for embedded pages.

Title bar

All four platforms use bare WebView containers. The SDK does not draw a title bar. Use onTitleChanged, visitorTitleChanged, or titleChanged to receive the web page title and draw your own AppBar outside the container. iOS observes webView.title with KVO, including title changes after switching conversations in the single-page app. Android uses onReceivedTitle and HarmonyOS uses onTitleReceive; both also fire when the title changes.

Keyboard and container appearance

The visitor page has a fixed 100dvh viewport. The container must shrink to avoid the keyboard, with a different implementation on each platform:

PlatformBehavior
AndroidApplies IME insets as padding to VisitorView (FrameLayout). VisitorKeyboardAvoidance uses WindowInsetsAnimationCompat to interpolate each frame. When the keyboard closes, it combines isVisible(ime) with the order in which insets arrive to determine the direction. On API levels below 30, it uses the system's adjustResize.
iOSChanges the WKWebView bottom constraint from safeAreaLayoutGuide to view.bottomAnchor with a variable constant. Calls layoutIfNeeded once in keyboardWillChangeFrame, without animation.
FlutterThe platform view handles the same insets. With the default Scaffold.resizeToAvoidBottomInset = true, overlap remains zero because Flutter shrinks the host container.
HarmonyOSArkWeb uses setKeyboardAvoidMode(RESIZE) and restores the host's previous mode when the page is destroyed.

Resizing the container recreates the WebKit/Blink rendering surface, so the keyboard may cause a one-frame flash. Eliminating it completely requires the H5 page to handle keyboard avoidance with visualViewport. On Android, insets must be applied to the parent container; padding on the WebView itself does not affect the H5 layout.

The container and WebView backgrounds follow the page palette: #F5F7F9 in light mode and #191919 in dark mode (VisitorChromePolicy.resolvePageBackground and VisitorView's paletteColor). This prevents a white background on the first frame or during resizing. iOS also sets isOpaque = false and clears the scrollView background.

The separate iOS page disables scrollView.bounces, alwaysBounceVertical, and alwaysBounceHorizontal so dragging the fixed viewport does not reveal blank space during overscroll.


Frequently asked questions​

Why does the page fail to open?

Check that the URL is HTTPS and that the query keys are valid. iOS also validates directChatId.

Why cannot site data be cleared?

IN_USE means a session is still active. Close every related page, wait for destruction to finish, and retry. iOS matches WebKit records by host, so sibling subdomains in the same record may also be cleared, but data is never cleared globally.

Why is an embedded Flutter page zero height?

Give VisitorView a definite height, for example by placing it inside Expanded.

How do I open a specific conversation directly?

Set directChatId.

How do I bind an already logged-in user?

Pass sbs, sbs_mm, and ranstr in query. Do not pass visitor_id.

How do I show a close button in the app?

Set isApp = true to show the in-page close button. Flutter receives a close event and the host must pop the page. The native Android and iOS SDKs currently do not forward this event, so the host must provide a back button. On HarmonyOS, the SDK exits a separate page; embedded pages do not forward the event.

How can the theme follow the system?

Initially use theme = system. Runtime changes can only switch to light or dark.

What about weak networks, backgrounding, lock screens, and WebSockets?

Verify these on real devices. The SDK does not add another network layer.

Why does Android throw IllegalArgumentException when opening?

start and embed validate the URL immediately. An empty or non-HTTPS URL, or a URL containing user:pass, throws. Catch the exception with try / catch in the button callback and display the error in the form instead of letting it reach the main thread.

Why does the status bar overlap my custom toolbar?

Android enforces edge-to-edge for targetSdk 35+. Apply padding from WindowInsetsCompat.Type.systemBars() to the root layout (applySystemBarInsets() in the sample).

Why is my custom title off-center?

Reserve equal-width space on both sides: the back button and the opposite placeholder must have the same width to center the title on the screen.

Why can users not exit the separate iOS page?

present opens a full-screen bare WebView without a system back gesture or close control. Provide a host button that calls handle.close() or dismiss, or wrap makeEmbeddedController in your own container with navigation controls. The native iOS SDK does not forward the page's close event.

Why does the separate HarmonyOS page fail to open with a missing VisitorPage log?

Import twt_visitor_sdk/src/main/ets/pages/VisitorPage once in the host entry point to register its named route.

Why does HarmonyOS start return null?

URL, query, or directChatId validation failed. An empty or non-HTTPS URL, user:pass credentials, or an invalid port returns null without opening a page.

Why are HarmonyOS cookies not cleared?

ArkWeb has no API for deleting cookies by site. clearSiteData clears only the target origin's Web Storage and does not clear cookies globally. Let the page finish logging out before switching accounts.

Why is there no microphone or camera permission prompt on HarmonyOS?

The HAR's permission declarations are insufficient on their own. Declare ohos.permission.MICROPHONE and ohos.permission.CAMERA in the host HAP's module.json5 as well.

Is a screenshot bridge or image clipboard supported?

There is no screenshot bridge. Image clipboard behavior is not guaranteed in all system WebViews.

Why does ohpm install twt_visitor_sdk report that the package does not exist?

Use version 0.0.4 (the central registry resolves exact versions) and confirm that the version has passed review. Run ohpm info twt_visitor_sdk to list available versions.

Why does HarmonyOS compilation report 00306046 Bytecode HAR not supported?

The HAR is a bytecode package. Keep strictMode.useNormalizedOHMUrl = true in the host project's build-profile.json5.

Why does the page flash when the keyboard opens?

See the keyboard and container appearance details in Runtime behavior. Resizing the container recreates the rendering surface; this is a known tradeoff.