Mobile app chat: developer guide
How to put a business's Ovelty chat inside their iOS or Android app: the ready-made chat screen in a WebView, one short screen of code on each platform.
Before you start
The business creates a Mobile app channel in Ovelty under Settings → Channels and sends you what you need: Copy for your developer there copies it as a ready message. You get:
- The chat screen link,
https://app.ovelty.com/widget/v1/mobile.html#appKey=ma_.... The part afterappKey=is the channel's app key. It is not a secret: it ships inside the app. - If the app has sign-in, the secret key, separately. It belongs on the app's server only and is never put in the app.
Once the app opens the chat for the first time, the channel's row in Ovelty shows it as connected, so the business can see the work is done.
The ready-made chat screen
Open the chat screen link in a WebView. Everything after the # stays on the phone: a URL fragment is never sent to a server, so nothing you put there lands in a log.
https://app.ovelty.com/widget/v1/mobile.html#appKey=ma_...
Add any of these after the app key, each as &name=value, with the value URL-encoded:
externalUserIdandidentityHash: for a signed-in customer, your own id for them and the hash your server computes,HMAC-SHA256(secretKey, externalUserId)in lower-case hex. Both or neither. With them, the customer has one conversation on every device and keeps it after a reinstall, and the agent sees the id with a check mark, under the name the business gives it in the channel (for example Customer ID), so they can look the person up in the business's own system.fullName: shown to the agent as the contact's name.emailAddress: for a signed-in customer, shown to the agent beside the id, marked as not verified. Neither is part of the hash, so neither is ever used to recognize anyone.platform,appVersion: shown to the agent under the channel, for exampleiosand2.3.1. Withoutplatform, the screen tells iOS from Android by itself.header=0: hides the screen's own title bar, for an app that shows its own. Recommended; see below.close=x: with the screen's own title bar, an X in place of the back arrow, for a chat the app presents as a sheet or pop-up.theme:lightordark, your app's own. Without it, the screen can follow the phone instead of your app, and a light app on a dark phone opens a dark chat.mic=1: shows a microphone, so the customer can record and send voice messages of up to two minutes. Add it only once the app grants the microphone, as below: without that permission the button could not record.lang: your app's language, for the screen's own words: English, Spanish, Russian, Turkish and Azerbaijani (en,es,ru,tr,az; a tag such ases-USworks). Without it, the phone's language is used, and English when it is none of these. Dates and times follow it too.
Which id to send. Your own record id for the person, one that never changes, such as the user id in your database. Not an email, phone number or username: when one of those changes, the chat sees a new person and the old conversation stays behind. Never a Social Security number, a national ID number (such as a FIN), a passport or a driver's license number: agents see the id, and a government number does not belong in a support tool.
Make it a screen of your app
Customers should not be able to tell where your app ends and the chat begins:
- Open the chat like any other screen: pushed on iOS, its own activity on Android. Not a dialog or a card over a dimmed screen, which reads as something foreign.
- Use your own top bar with a back arrow and a title such as Support, and pass
header=0. If your app has no top bar, leave the chat's own: it shows the platform's back arrow when the app has theoveltyhandler below. The iOS code registers it; on Android, addaddJavascriptInterface(object { @JavascriptInterface fun postMessage(json: String) = runOnUiThread { finish() } }, "ovelty")to the WebView. - Pass your app's
themeandlang, as the code below does. - Keep the chat clear of the status bar, the navigation bar and the keyboard. On Android 15 every app is edge to edge; the code below handles it with the top bar's padding and
imePadding(), which needsandroid:windowSoftInputMode="adjustResize"on the activity in your manifest.
The WebView needs these things from the app:
- JavaScript turned on, and on Android DOM storage too. Storage is where the screen keeps the device key that brings an anonymous customer back to their conversation; without it, every launch starts a new one.
- Links and documents opened outside the chat. They open with
target="_blank"; hand them to Safari or the browser, as in the code below. Pictures open full size inside the screen. - On Android, a file chooser, so the paperclip can pick photos or files. On iOS the paperclip also offers the camera, so the app's Info.plist needs
NSCameraUsageDescriptionandNSMicrophoneUsageDescription; without them the app closes when a customer picks it. - For voice messages, the microphone, and
mic=1in the link. On iOS,NSMicrophoneUsageDescription(already there for the camera) and the media-capture method ofWKUIDelegatein the code below, so the customer is asked once, by your app, and not a second time by the page. On Android,RECORD_AUDIOandMODIFY_AUDIO_SETTINGSin the manifest, the permission asked for when the customer first taps the microphone, andonPermissionRequestgranting audio capture, as below. - Optionally, a handler named
ovelty. When the app has one and keeps the chat's own title bar, the screen shows a back button and posts{ "type": "close" }to it when tapped.
On iOS:
import UIKit
import WebKit
import SafariServices
// Push it like any other screen of your app:
// navigationController?.pushViewController(SupportChatViewController(), animated: true)
final class SupportChatViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler {
// From your server for a signed-in customer; leave both nil for a guest.
var userId: String?
var identityHash: String?
private let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
override func viewDidLoad() {
super.viewDidLoad()
title = "Support" // your navigation bar is the chat's title bar
webView.frame = view.bounds
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.uiDelegate = self
// Weakly held, so the WebView does not keep this screen alive after it closes.
webView.configuration.userContentController.add(WeakHandler(self), name: "ovelty")
view.addSubview(webView)
// Your app's own light or dark and language, so the chat looks and reads like the rest of it.
let theme = traitCollection.userInterfaceStyle == .dark ? "dark" : "light"
let lang = Bundle.main.preferredLocalizations.first ?? "en"
var fragment = "appKey=ma_YOUR_APP_KEY&platform=ios&header=0&mic=1&theme=\(theme)&lang=\(lang)"
if let userId, let identityHash {
let id = userId.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? userId
fragment += "&externalUserId=\(id)&identityHash=\(identityHash)"
}
webView.load(URLRequest(url: URL(string: "https://app.ovelty.com/widget/v1/mobile.html#\(fragment)")!))
}
deinit {
webView.configuration.userContentController.removeScriptMessageHandler(forName: "ovelty")
}
// Links and documents from the chat open in Safari, not inside the chat.
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration,
for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if let url = action.request.url { present(SFSafariViewController(url: url), animated: true) }
return nil
}
// Voice messages (mic=1). iOS asks the customer once for your app, using NSMicrophoneUsageDescription;
// this stops the page from asking a second time. Only for the chat itself.
func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin,
initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType,
decisionHandler: @escaping (WKPermissionDecision) -> Void) {
decisionHandler(origin.host == "app.ovelty.com" && type == .microphone ? .grant : .deny)
}
// Only reached if you keep the chat's own title bar (no header=0): its back button.
func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
if let navigation = navigationController, navigation.viewControllers.first != self {
navigation.popViewController(animated: true)
} else {
dismiss(animated: true)
}
}
}
private final class WeakHandler: NSObject, WKScriptMessageHandler {
weak var target: WKScriptMessageHandler?
init(_ target: WKScriptMessageHandler) { self.target = target }
func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
target?.userContentController(controller, didReceive: message)
}
}
On Android:
// Jetpack Compose, with androidx.activity:activity-compose, Material 3 and
// androidx.compose.material:material-icons-core. Open it like any other screen of your app:
// startActivity(Intent(this, SupportChatActivity::class.java))
class SupportChatActivity : ComponentActivity() {
private var fileCallback: ValueCallback<Array<Uri>>? = null
// Voice messages (mic=1). In the manifest: <uses-permission android:name="android.permission.RECORD_AUDIO" />
// and <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />.
private var pendingMicrophone: PermissionRequest? = null
private val askMicrophone = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
pendingMicrophone?.let { if (granted) it.grant(arrayOf(PermissionRequest.RESOURCE_AUDIO_CAPTURE)) else it.deny() }
pendingMicrophone = null
}
// The chat asks when the customer taps the microphone; the app asks Android the first time.
private fun onMicrophone(request: PermissionRequest) {
if (request.origin.host != "app.ovelty.com" || PermissionRequest.RESOURCE_AUDIO_CAPTURE !in request.resources) {
request.deny()
} else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
request.grant(arrayOf(PermissionRequest.RESOURCE_AUDIO_CAPTURE))
} else {
pendingMicrophone?.deny()
pendingMicrophone = request
askMicrophone.launch(Manifest.permission.RECORD_AUDIO)
}
}
// The paperclip allows several files; a picker returns those in clipData, a single one in data.
private val pickFile = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val data = result.data
val picked = data?.clipData?.let { clip -> Array(clip.itemCount) { clip.getItemAt(it).uri } }
?: WebChromeClient.FileChooserParams.parseResult(result.resultCode, data)
fileCallback?.onReceiveValue(if (result.resultCode == RESULT_OK) picked else null)
fileCallback = null
}
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
// Your app's own light or dark and language, so the chat looks and reads like the rest of it.
// isSystemInDarkTheme() follows the phone; if your app has its own light/dark setting, use that.
val dark = isSystemInDarkTheme()
val lang = LocalConfiguration.current.locales[0].toLanguageTag()
// For a signed-in customer, add "&externalUserId=…&identityHash=…" from your server.
val url = "https://app.ovelty.com/widget/v1/mobile.html#appKey=ma_YOUR_APP_KEY&platform=android" +
"&header=0&mic=1&theme=${if (dark) "dark" else "light"}&lang=$lang"
YourAppTheme {
SupportChatScreen(url, dark, onBack = ::finish, onMicrophone = ::onMicrophone, onPickFile = { callback, params ->
fileCallback?.onReceiveValue(null)
fileCallback = callback
pickFile.launch(params.createIntent())
})
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun SupportChatScreen(
url: String,
dark: Boolean,
onBack: () -> Unit,
onMicrophone: (PermissionRequest) -> Unit,
onPickFile: (ValueCallback<Array<Uri>>, WebChromeClient.FileChooserParams) -> Unit,
) {
// The chat's own background behind the navigation bar and under the WebView while it loads,
// so no strip of another colour shows below the message box.
val chatBackground = if (dark) Color(0xFF111318) else Color.White
Scaffold(
containerColor = chatBackground,
topBar = {
TopAppBar(
title = { Text("Support") },
navigationIcon = {
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") }
},
)
},
) { padding ->
AndroidView(
// Below your top bar, above the navigation bar and the keyboard.
modifier = Modifier.fillMaxSize().padding(padding).consumeWindowInsets(padding).imePadding(),
factory = { context ->
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
setBackgroundColor(chatBackground.toArgb())
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.setSupportMultipleWindows(true)
webChromeClient = object : WebChromeClient() {
// Links and documents from the chat open in the browser, not inside the chat.
override fun onCreateWindow(view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message): Boolean {
val popup = WebView(view.context)
popup.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(v: WebView, request: WebResourceRequest): Boolean {
v.context.startActivity(Intent(Intent.ACTION_VIEW, request.url))
v.destroy()
return true
}
}
(resultMsg.obj as WebView.WebViewTransport).webView = popup
resultMsg.sendToTarget()
return true
}
// The paperclip.
override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean {
onPickFile(callback, params)
return true
}
// The microphone, for voice messages.
override fun onPermissionRequest(request: PermissionRequest) = onMicrophone(request)
}
loadUrl(url)
}
},
onRelease = { it.destroy() },
)
}
}
If you would rather use the chat's own title bar
For an app without a top bar of its own, the chat can draw it: leave out header=0. The title bar then shows the channel's chat title, a back arrow in the platform's own style (a chevron on iOS, an arrow on Android), and "Typing…" while an agent writes. Theme, language and the channel's color work as above. Two things stay with the app:
- The
oveltyhandler. The back button only appears when the app has it, because closing the screen is the app's job. Addclose=xto show an X instead, for a chat you present as a sheet or full-screen pop-up rather than push. - The status bar. On iOS the chat keeps clear of it by itself. On Android, older WebViews do not tell the page where the status bar is, so the app pads the WebView and paints the strips behind the status and navigation bars in the chat's own background, as below.
On iOS:
// The same SupportChatViewController, with these changes:
// 1. In viewDidLoad: no title of your own, and the chat lays itself out under the status bar.
webView.scrollView.contentInsetAdjustmentBehavior = .never
// 2. The fragment: no header=0. Add close=x when you present the chat rather than push it.
var fragment = "appKey=ma_YOUR_APP_KEY&platform=ios&mic=1&theme=\(theme)&lang=\(lang)&close=x"
// 3. Present it; the chat's X calls the "ovelty" handler, which dismisses it.
let chat = SupportChatViewController()
chat.modalPresentationStyle = .fullScreen // or .pageSheet, which also closes with a swipe down
present(chat, animated: true)
On Android:
// Jetpack Compose, with androidx.activity:activity-compose. Open it like any other screen of your app:
// startActivity(Intent(this, SupportChatActivity::class.java))
// In the manifest: <activity android:name=".SupportChatActivity" android:windowSoftInputMode="adjustResize" />
class SupportChatActivity : ComponentActivity() {
private var fileCallback: ValueCallback<Array<Uri>>? = null
// Voice messages (mic=1). In the manifest: <uses-permission android:name="android.permission.RECORD_AUDIO" />
// and <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />.
private var pendingMicrophone: PermissionRequest? = null
private val askMicrophone = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
pendingMicrophone?.let { if (granted) it.grant(arrayOf(PermissionRequest.RESOURCE_AUDIO_CAPTURE)) else it.deny() }
pendingMicrophone = null
}
// The chat asks when the customer taps the microphone; the app asks Android the first time.
private fun onMicrophone(request: PermissionRequest) {
if (request.origin.host != "app.ovelty.com" || PermissionRequest.RESOURCE_AUDIO_CAPTURE !in request.resources) {
request.deny()
} else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
request.grant(arrayOf(PermissionRequest.RESOURCE_AUDIO_CAPTURE))
} else {
pendingMicrophone?.deny()
pendingMicrophone = request
askMicrophone.launch(Manifest.permission.RECORD_AUDIO)
}
}
// The paperclip allows several files; a picker returns those in clipData, a single one in data.
private val pickFile = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val data = result.data
val picked = data?.clipData?.let { clip -> Array(clip.itemCount) { clip.getItemAt(it).uri } }
?: WebChromeClient.FileChooserParams.parseResult(result.resultCode, data)
fileCallback?.onReceiveValue(if (result.resultCode == RESULT_OK) picked else null)
fileCallback = null
}
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
// Your app's own light or dark and language. isSystemInDarkTheme() follows the phone;
// if your app has its own light/dark setting, use that.
val dark = isSystemInDarkTheme()
val lang = LocalConfiguration.current.locales[0].toLanguageTag()
// No header=0: the chat draws its own title bar, with a back arrow.
// For a signed-in customer, add "&externalUserId=…&identityHash=…" from your server.
val url = "https://app.ovelty.com/widget/v1/mobile.html#appKey=ma_YOUR_APP_KEY&platform=android" +
"&mic=1&theme=${if (dark) "dark" else "light"}&lang=$lang"
// The strips behind the status bar and the navigation bar take the chat's own background,
// so its title bar runs up to the top of the screen.
val chatBackground = if (dark) Color(0xFF111318) else Color.White
Box(Modifier.fillMaxSize().background(chatBackground).systemBarsPadding().imePadding()) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { context ->
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
setBackgroundColor(chatBackground.toArgb())
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.setSupportMultipleWindows(true)
webChromeClient = object : WebChromeClient() {
// Links and documents from the chat open in the browser, not inside the chat.
override fun onCreateWindow(view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message): Boolean {
val popup = WebView(view.context)
popup.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(v: WebView, request: WebResourceRequest): Boolean {
v.context.startActivity(Intent(Intent.ACTION_VIEW, request.url))
v.destroy()
return true
}
}
(resultMsg.obj as WebView.WebViewTransport).webView = popup
resultMsg.sendToTarget()
return true
}
// The paperclip.
override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean {
fileCallback?.onReceiveValue(null)
fileCallback = callback
pickFile.launch(params.createIntent())
return true
}
// The microphone, for voice messages.
override fun onPermissionRequest(request: PermissionRequest) = onMicrophone(request)
}
// The chat's back button. Called on a background thread, hence post.
addJavascriptInterface(object {
@JavascriptInterface fun postMessage(json: String) { post { finish() } }
}, "ovelty")
loadUrl(url)
}
},
onRelease = { it.destroy() },
)
}
}
}
}
Replies reach the screen live while it is open. A reply sent while the chat was closed is waiting in the conversation the next time it is opened.
A screen of your own
The ready-made screen covers messages, photos and files, voice messages, live replies, typing dots and read receipts. If you need a native chat screen of your own design instead, write to support@ovelty.com and we will send you the API.
Questions while you build: support@ovelty.com. For the business side, see Mobile app chat.