Appearance
Integrating the Chatbot into an Android App
This guide covers putting the Pleased chatbot inside an Android app, in a WebView.
For iOS, see iOS Integration.
It assumes you have already done Getting Started and have your data-pls-client-id and data-pls-widget-id.
How this differs from a website
On the web you add one <script> tag to a page you already have. An app has no page, and a WebView loads a document, not a script — so the first thing you need is something for the loader to live in. Pleased hosts that page for you.
Everything else is the same widget, talking to the same backend.
You will add:
| three manifest permissions | network access, and the microphone |
| two Kotlin files | WebView setup, and a bridge for driving the widget from your app |
| a URL | the page your WebView loads |
minSdk 21 or higher. Nothing else is required — no libraries, no Gradle changes.
Step 1: Add the permissions
All three, in AndroidManifest.xml:
xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />MODIFY_AUDIO_SETTINGS is not optional
It is an install-time permission, so it never appears in a runtime prompt and nothing will tell you it is missing. Without it the microphone permission is granted, every check passes, and the chatbot still fails with NotReadableError — Could not start audio source, which reads like broken hardware. This is the single most common mistake in an Android integration.
Skip the two audio permissions only if you are certain you will never enable voice calls.
Step 2: Add the two Kotlin files
Copy these into your project. They depend on framework API only — no libraries, no Gradle changes.
PleasedWebViewSetup.kt
Configures the WebView and answers microphone requests.
kotlin
package com.pleased.client
import android.Manifest
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.webkit.ConsoleMessage
import android.webkit.PermissionRequest
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
/**
* WebView setup for the Pleased chatbot. Copy this file as-is.
*
* ```
* private lateinit var pleased: PleasedWebViewSetup
*
* pleased = PleasedWebViewSetup(this, webView).apply { configure() }
* webView.loadUrl(hostPageUrl)
*
* override fun onRequestPermissionsResult(code: Int, perms: Array<out String>, results: IntArray) {
* super.onRequestPermissionsResult(code, perms, results)
* pleased.onRequestPermissionsResult(code, results)
* }
*
* override fun onActivityResult(code: Int, result: Int, data: Intent?) {
* super.onActivityResult(code, result, data)
* pleased.onActivityResult(code, result, data) // the chat's attach-file button
* }
* ```
*
* Add BOTH permissions to your manifest:
* ```
* <uses-permission android:name="android.permission.RECORD_AUDIO" />
* <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
* ```
*
* `MODIFY_AUDIO_SETTINGS` is not optional. It is install-time, so it never appears in a prompt,
* and without it `getUserMedia` fails with `NotReadableError` even once RECORD_AUDIO is granted.
*
* One instance per WebView. Depends on framework API only.
*
* @param widgetOrigins origins allowed to use the microphone, besides the page you load. The
* chatbot asks from the widget's own iframe, so this must contain wherever the widget is
* served from. Override it if you self-host the loader.
*/
class PleasedWebViewSetup(
private val activity: Activity,
private val webView: WebView,
private val widgetOrigins: Set<String> = DEFAULT_WIDGET_ORIGINS,
) {
/**
* The page this WebView is for, pinned once its first load has FINISHED — so the whole
* redirect chain of that first navigation is allowed, and everything after is measured
* against where you actually ended up. Compared without the fragment, which never loads a
* page.
*
* The URL, not just the origin: origin-only would let a link to a neighbouring path on the
* same host keep the bridge and the microphone handler, which matters as soon as your host
* page shares an origin with anything you do not control.
*/
private var pinnedUrl: String? = null
private var pendingRequest: PermissionRequest? = null
private var pendingFiles: ValueCallback<Array<Uri>>? = null
fun configure() {
// chrome://inspect, in debug builds only — it exposes the page to anything that can
// reach the device.
if ((activity.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
WebView.setWebContentsDebuggingEnabled(true)
}
webView.settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
// Without this the WebView can send audio but never play any back.
mediaPlaybackRequiresUserGesture = false
}
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
// The first load has settled, redirects included. That is the page.
if (pinnedUrl == null) pinnedUrl = withoutFragment(url)
}
/**
* The backstop, and not redundant with [shouldOverrideUrlLoading]: Android does not
* consult that method for every main-frame navigation — a POST, or some redirects,
* arrive here having never been offered for approval.
*/
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
val pinned = pinnedUrl ?: return
if (withoutFragment(url) == pinned) return
view.stopLoading()
leaveWebView(url)
}
/**
* Keeps this WebView on the page you loaded, because it is not an ordinary WebView:
* it carries a JavaScript bridge that reaches your token callback, and it answers
* microphone requests. Off-site navigation goes to the browser, which has neither.
*/
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
// Sub-frames are the widget's iframe and what it loads, never a navigation of
// this WebView.
if (!request.isForMainFrame) return false
val pinned = pinnedUrl ?: return false
val target = request.url?.toString() ?: return true
if (withoutFragment(target) == pinned) return false
leaveWebView(target)
return true
}
}
webView.webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(message: ConsoleMessage): Boolean = false
override fun onPermissionRequest(request: PermissionRequest) {
// Not overriding this is not a neutral choice: the base implementation denies,
// with no prompt and no log.
answerAudioPermission(request)
}
override fun onPermissionRequestCanceled(request: PermissionRequest) {
if (pendingRequest == request) pendingRequest = null
}
/**
* The chat's attach-file button is an `<input type="file">`. A WebView has no picker
* of its own: the base implementation returns false and the tap does nothing — no
* error, no log. iOS needs no equivalent; WKWebView shows its own picker.
*/
override fun onShowFileChooser(
view: WebView,
filePathCallback: ValueCallback<Array<Uri>>,
params: FileChooserParams,
): Boolean {
// One chooser at a time. An older callback left unanswered keeps that input
// dead until the page reloads, so release it first.
pendingFiles?.onReceiveValue(null)
pendingFiles = filePathCallback
return try {
activity.startActivityForResult(params.createIntent(), REQUEST_CODE_FILE_CHOOSER)
true
} catch (e: ActivityNotFoundException) {
// Returning false cancels on the WebView's side; the callback must then
// stay unanswered.
pendingFiles = null
false
}
}
}
}
/**
* Call from your Activity's `onActivityResult`. Returns true if this was the file picker
* this WebView opened.
*/
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
if (requestCode != REQUEST_CODE_FILE_CHOOSER) return false
val callback = pendingFiles ?: return false
pendingFiles = null
// Always answer, a cancel included (null) — see onShowFileChooser.
callback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data))
return true
}
/**
* Call from your Activity's `onRequestPermissionsResult`. Returns true if this WebView was
* the one waiting, so an Activity with more than one can offer the result to each.
*/
fun onRequestPermissionsResult(requestCode: Int, grantResults: IntArray): Boolean {
if (requestCode != REQUEST_CODE_RECORD_AUDIO) return false
val request = pendingRequest ?: return false
pendingRequest = null
val granted = grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
if (granted) request.grant(AUDIO_ONLY) else request.deny()
return true
}
internal fun answerAudioPermission(request: PermissionRequest) {
// This origin is the frame that asked — for the chatbot, the widget's iframe, NOT the
// page you loaded. Comparing it to your own URL refuses every working integration.
//
// A request with no identifiable origin is refused outright. Letting it reach the
// comparison would grant it whenever nothing is pinned yet, since null equals null.
val origin = originOf(request.origin?.toString())
if (origin == null || (origin != originOf(pinnedUrl) && origin !in widgetOrigins)) {
request.deny()
return
}
if (!request.resources.contains(PermissionRequest.RESOURCE_AUDIO_CAPTURE)) {
request.deny()
return
}
// Runtime permissions arrived in API 23. Below that, a permission in the manifest is
// granted at install time and there is nothing to ask for — and both checkSelfPermission
// and requestPermissions are API 23, so reaching them on an older device throws
// NoSuchMethodError. Without this the whole class needs minSdk 23.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
request.grant(AUDIO_ONLY)
return
}
// Audio only. `request.resources` is whatever the page asked for, so handing it back
// would grant the camera off the strength of a RECORD_AUDIO check.
if (activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED
) {
request.grant(AUDIO_ONLY)
return
}
// Just ask. shouldShowRequestPermissionRationale() cannot tell you whether a prompt will
// appear — it returns false for never-asked, permanently-denied AND "Ask every time" —
// so any pre-check eventually refuses someone the OS would have prompted. A permission
// that really is permanently denied is answered at once, with no UI.
pendingRequest = request
activity.requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), REQUEST_CODE_RECORD_AUDIO)
}
/** Hand a URL to the browser. Failing to launch is not a reason to load it here instead. */
private fun leaveWebView(url: String) {
runCatching { activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }
}
companion object {
const val REQUEST_CODE_RECORD_AUDIO = 4371
const val REQUEST_CODE_FILE_CHOOSER = 4372
/** Where the Pleased widget is served from — the host of your loader script. */
val DEFAULT_WIDGET_ORIGINS = setOf("https://cdn.pleased.com")
private val AUDIO_ONLY = arrayOf(PermissionRequest.RESOURCE_AUDIO_CAPTURE)
/** Fragments never load a page, so they must not count as navigating away. */
private fun withoutFragment(url: String) = url.substringBefore('#')
internal fun originOf(url: String?): String? = url
?.let { runCatching { Uri.parse(it) }.getOrNull() }
?.let { uri -> uri.scheme?.let { scheme -> uri.authority?.let { "$scheme://$it" } } }
}
}PleasedBridge.kt
Lets your app drive the widget — supplying the visitor's token, opening the chat, listening for events. Skip this file if you only want to display the chatbot and never talk to it.
kotlin
package com.pleased.client
import android.webkit.JavascriptInterface
import android.webkit.WebView
import java.util.concurrent.ConcurrentHashMap
import org.json.JSONObject
import org.json.JSONTokener
/**
* Drives the Pleased loader running inside a WebView. Copy this file as-is.
*
* ```
* val bridge = PleasedBridge(webView) // BEFORE loadUrl
* val pleased = PleasedWebViewSetup(this, webView).apply { configure() }
* webView.loadUrl(hostPageUrl)
*
* bridge.onLoaderReady = {
* bridge.registerCallback("set:callback", "token") { _, respond ->
* fetchToken { respond.resolve(JSONObject.quote(it)) } // async is fine
* }
* bridge.registerCallback("event:on", "ready") { _, _ -> bridge.invoke("widget:open", "{}") }
* }
* ```
*
* Commands pass through as strings, so a new `set:` or event needs no change here. The list of
* what you can send is in the integration guide, not duplicated in Kotlin.
*/
class PleasedBridge(private val webView: WebView) {
/**
* Called on the main thread, so it is safe to touch UI, start an Activity or read anything
* with thread affinity straight from here.
*
* Answer through [respond] exactly once. Async is fine — the widget gives up after 10s.
* For `event:on` / `event:once` there is nothing to answer and [respond] does nothing.
*/
fun interface CallbackHandler {
fun handle(payloadJson: String?, respond: Responder)
}
interface Responder {
/** [valueJson] must be valid JSON. A bare string needs `JSONObject.quote(value)`. */
fun resolve(valueJson: String?)
fun reject(error: String)
}
/** Fires once the loader script has run. Register your callbacks here. */
var onLoaderReady: (() -> Unit)? = null
// @JavascriptInterface arrives on a background thread while registerCallback writes from
// the UI thread; a plain HashMap loses registrations under that race.
private val handlers = ConcurrentHashMap<String, CallbackHandler>()
init {
// Must be attached before the page loads, or every callback rejects with
// "no native bridge attached".
webView.addJavascriptInterface(NativeInterface(), "PleasedNative")
}
/**
* Run any loader command. [onResult] gets the JSON `{ok, result}` the page returned, or
* `{ok: false, error}` without reaching the page when [payloadJson] is not JSON.
*/
fun invoke(command: String, payloadJson: String? = null, onResult: ((String) -> Unit)? = null) {
// Caught here rather than by JSON.parse in the page, so the error names the real cause
// and arrives before anything is evaluated. Empty means "no payload", as in the page.
if (!payloadJson.isNullOrEmpty() && runCatching { JSONTokener(payloadJson).nextValue() }.isFailure) {
val error = JSONObject().put("ok", false).put("error", "payloadJson is not valid JSON").toString()
onResult?.let { webView.post { it(error) } }
return
}
val js = "window.__plInvoke(${JSONObject.quote(command)}, " +
(payloadJson?.let { JSONObject.quote(it) } ?: "null") + ")"
eval(js, onResult)
}
/**
* [type] is the loader command verbatim: `set:callback` for values the widget asks for,
* `event:on` / `event:once` to subscribe. Name an event `*` to receive all of them, as
* `{"event":..., "payload":...}`.
*/
fun registerCallback(type: String, name: String, handler: CallbackHandler) {
handlers["$type|$name"] = handler
eval("window.__plAddCallback(${JSONObject.quote(type)}, ${JSONObject.quote(name)})")
}
fun removeCallback(type: String, name: String) {
handlers.remove("$type|$name")
eval("window.__plRemoveCallback(${JSONObject.quote(type)}, ${JSONObject.quote(name)})")
}
private fun eval(js: String, onResult: ((String) -> Unit)? = null) {
// evaluateJavascript must run on the UI thread, and @JavascriptInterface methods are
// delivered on a background one, so this post is load-bearing rather than tidy.
webView.post { webView.evaluateJavascript(js) { result -> onResult?.invoke(unwrap(result)) } }
}
/**
* evaluateJavascript JSON-encodes what the page returned, and the shim returns a JSON
* string — so results arrive twice-encoded and `JSONObject(it)` throws. Undo one layer.
*/
private fun unwrap(raw: String?): String {
val value = raw ?: return "null"
val decoded = runCatching { JSONTokener(value).nextValue() }.getOrNull()
return if (decoded is String) decoded else value
}
/**
* Hands work to the main thread.
*
* `@JavascriptInterface` methods are delivered on a WebView background thread. Running a
* client's handler there would mean their token lookup, their Activity start, their view
* update — all off the UI thread, crashing somewhere far from the cause. Everything the
* page sends in crosses back here first.
*/
private fun onMain(block: () -> Unit) {
webView.post(block)
}
private inner class NativeInterface {
@JavascriptInterface
fun onMessage(json: String) {
val message = runCatching { JSONObject(json) }.getOrNull() ?: return
when (message.optString("kind")) {
"loader_ready" -> onMain { onLoaderReady?.invoke() }
"event" -> {
val name = message.optString("name")
val raw = message.opt("payload")?.takeIf { it != JSONObject.NULL }
// One delivery per subscription, and `via` says which one — so a host
// registered twice for the same event (event:on and event:once, or a name
// and "*") runs each handler once rather than every handler every time.
val via = message.optString("via")
when {
// A wildcard delivery names the event, not the subscription, so it is
// keyed by "*" and the name travels inside an envelope — a wildcard
// handler cannot tell what it received without it. `via` still says
// which subscription, which is what keeps event:on "*" and
// event:once "*" apart.
message.optBoolean("wildcard") -> {
val envelope = JSONObject()
.put("event", name)
.put("payload", raw ?: JSONObject.NULL)
.toString()
onMain { handlers["$via|*"]?.handle(envelope, NoopResponder) }
}
via.isEmpty() -> onMain {
// No `via`: an older host page than this bridge. Fall back to the
// previous behaviour rather than dropping the event.
handlers["event:on|$name"]?.handle(raw?.toString(), NoopResponder)
handlers["event:once|$name"]?.handle(raw?.toString(), NoopResponder)
}
else -> onMain { handlers["$via|$name"]?.handle(raw?.toString(), NoopResponder) }
}
}
"callback" -> {
val name = message.optString("name")
val id = message.optString("id")
val type = message.optString("type")
val payload = message.opt("payload")?.takeIf { it != JSONObject.NULL }?.toString()
val handler = handlers["$type|$name"]
if (handler == null) {
reject(id, "no handler registered for $name")
return
}
onMain { handler.handle(payload, JsResponder(id)) }
}
}
}
}
private fun resolve(id: String, valueJson: String?) {
eval(
"window.__plResolveCallback(${JSONObject.quote(id)}, " +
(valueJson?.let { JSONObject.quote(it) } ?: "null") + ")"
)
}
private fun reject(id: String, error: String) {
eval("window.__plRejectCallback(${JSONObject.quote(id)}, ${JSONObject.quote(error)})")
}
private inner class JsResponder(private val id: String) : Responder {
private var settled = false
override fun resolve(valueJson: String?) {
if (settled) return
settled = true
this@PleasedBridge.resolve(id, valueJson)
}
override fun reject(error: String) {
if (settled) return
settled = true
this@PleasedBridge.reject(id, error)
}
}
private object NoopResponder : Responder {
override fun resolve(valueJson: String?) = Unit
override fun reject(error: String) = Unit
}
}Step 3: Load the page
This much displays the chatbot. Step 4 extends this same Activity to drive it — supplying the visitor's token, opening the chat, listening for events — and shows the finished version.
kotlin
class ChatActivity : Activity() {
private lateinit var webView: WebView
private lateinit var pleased: PleasedWebViewSetup
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
webView = WebView(this)
setContentView(webView)
pleased = PleasedWebViewSetup(this, webView).apply { configure() }
webView.loadUrl(
"https://cdn.pleased.com/widget/native/index.html" +
"?clientId=YOUR_CLIENT_ID&widgetId=YOUR_WIDGET_ID&platform=app"
)
}
override fun onRequestPermissionsResult(
code: Int,
permissions: Array<out String>,
results: IntArray,
) {
super.onRequestPermissionsResult(code, permissions, results)
pleased.onRequestPermissionsResult(code, results)
}
override fun onActivityResult(code: Int, result: Int, data: Intent?) {
super.onActivityResult(code, result, data)
pleased.onActivityResult(code, result, data)
}
}A few things worth knowing:
- Host it in an Activity with no ActionBar. From
targetSdk35 the window sits behind the system bars, so theWebViewgets the whole screen and anything in your theme's decor is painted over the page — an ActionBar covers the widget's greeting and its close control, leaving the visitor no way out but the back button.fitsSystemWindowsdoes not help, because the ActionBar is not a system bar. UseTheme.*.NoActionBaron this Activity, or keep whatever you draw clear of theWebView. platform=appmatters. It tells the widget your app owns the launcher, so it does not draw its own bubble over your UI. Useioson iOS.- Owning the launcher means owning the way back. Because there is no bubble, closing the chat leaves nothing on screen to reopen it — the widget emits
closeand hides, and what happens next is yours to decide. Handle it or the visitor is left staring at an emptyWebViewwith only the back button. Step 4 shows the handler. - Keep the
PleasedWebViewSetupinstance. It holds the in-flight permission request, soonRequestPermissionsResulthas to reach that same object. One instance perWebView. - Forwarding
onRequestPermissionsResultis required. Without it the microphone prompt appears, the visitor taps Allow, and nothing happens. - Forwarding
onActivityResultis required for attachments. The chat's attach button is a file input, and an AndroidWebViewhas no file picker of its own:PleasedWebViewSetupopens the system one and needs the result back. Without it the picker opens, the visitor chooses a file, and nothing is attached. See Attaching files.
Hosting the page yourself
If you would rather serve the page from your own domain, it is two tags and no glue:
html
<script
src="https://cdn.pleased.com/widget/pl-loader.min.js"
data-pls-client-id="YOUR_CLIENT_ID"
data-pls-widget-id="YOUR_WIDGET_ID"
data-pls-platform="app"
></script>
<script src="https://cdn.pleased.com/widget/native/pl-native.js"></script>The order matters
Browsers run these in document order, so pl-native.js finds the loader already there and tells your app it is ready — which is what PleasedBridge.onLoaderReady waits for. Put pl-native.js first and nothing will announce it.
If you inject the loader from your own script instead, say so explicitly: loaderScript.onload = window.__plAnnounceLoaderReady.
You must serve the page over HTTPS. Microphone access requires a secure context, and the request is refused before the visitor is ever asked.
Step 4: Drive the widget from your app
Create the bridge before loadUrl — the page looks for it as soon as it runs.
This is Step 3's Activity with the bridge added, complete. It replaces the one above rather than being appended to it:
kotlin
class ChatActivity : Activity() {
private lateinit var webView: WebView
private lateinit var pleased: PleasedWebViewSetup
private lateinit var bridge: PleasedBridge
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
webView = WebView(this)
setContentView(webView)
// Before configure() and before loadUrl: the page looks for the bridge as soon as it runs.
bridge = PleasedBridge(webView)
bridge.onLoaderReady = {
// The widget asks for the signed-in visitor's token. Return "" for a guest.
// See Widget Auth for how to produce this token on your backend.
bridge.registerCallback("set:callback", "token") { _, respond ->
fetchTokenFromYourBackend { token ->
respond.resolve(JSONObject.quote(token)) // async is fine
}
}
bridge.registerCallback("event:on", "ready") { _, _ ->
bridge.invoke("widget:open", "{}")
}
// Required, not optional — see below.
bridge.registerCallback("event:on", "close") { _, _ -> finish() }
// The way back from a blocked microphone — see "When the microphone is blocked".
bridge.registerCallback("event:on", "request_open_settings") { _, _ ->
startActivity(
Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", packageName, null),
)
)
}
bridge.invoke("set:config", """{"capabilities":{"canOpenAppSettings":true}}""")
}
pleased = PleasedWebViewSetup(this, webView).apply { configure() }
webView.loadUrl(
"https://cdn.pleased.com/widget/native/index.html" +
"?clientId=YOUR_CLIENT_ID&widgetId=YOUR_WIDGET_ID&platform=app"
)
}
override fun onRequestPermissionsResult(
code: Int,
permissions: Array<out String>,
results: IntArray,
) {
super.onRequestPermissionsResult(code, permissions, results)
pleased.onRequestPermissionsResult(code, results)
}
override fun onActivityResult(code: Int, result: Int, data: Intent?) {
super.onActivityResult(code, result, data)
pleased.onActivityResult(code, result, data)
}
}Closing the chat
platform=app suppresses the widget's own bubble, which is what stops it drawing over your UI — but it also means the widget has no way to bring itself back. When the visitor minimises the chat it emits close and hides, and unless you do something the screen is simply empty.
What to do depends on where you put the WebView:
| Where the chat lives | On close |
|---|---|
| Its own Activity, as above | finish() — back to the screen that opened it |
| Inside a screen you already have | hide the WebView, show your own entry point |
Either way it is your code. Reopening later is bridge.invoke("widget:open", "{}"), or a fresh Activity — the widget does not remember it was closed.
Read Widget Auth and Widget Token for the token itself — the Android side only has to hand over whatever your backend produced.
Commands
Anything from the Widget API works, passed through as a string:
kotlin
bridge.invoke("widget:open")
bridge.invoke("widget:close")
bridge.invoke("widget:re_auth") // visitor signed in or out
bridge.invoke("chat:end")
bridge.invoke("get:is_open") { result -> /* {"ok":true,"result":true} */ }get: commands answer through the callback; the rest return null.
Events
kotlin
bridge.registerCallback("event:on", "on_chat:start") { payload, _ -> /* … */ }Or subscribe to everything, including events added after you ship:
kotlin
bridge.registerCallback("event:on", "*") { payload, _ ->
// payload is {"event":"ready","payload":null}
Log.i("Pleased", payload.orEmpty())
}To stop listening, call removeCallback with the same type you registered with — event:on or event:once, never event:off. The bridge sends event:off for you; it holds the JavaScript function the loader needs, which your app cannot:
kotlin
bridge.registerCallback("event:on", "on_chat:start") { payload, _ -> /* … */ }
// later
bridge.removeCallback("event:on", "on_chat:start")
bridge.registerCallback("event:once", "ready") { _, _ -> /* … */ }
bridge.removeCallback("event:once", "ready") // works whether or not it has fired
bridge.removeCallback("set:callback", "token") // the widget then treats the visitor as a guestOne handler per type and name: registering event:on close again replaces the previous one.
See Widget Events for the list.
Bridge reference
PleasedBridge | Use for |
|---|---|
onLoaderReady | register everything below; runs once the loader is up |
invoke(command, payloadJson?, onResult?) | every widget:, chat:, get: and set: command except set:callback. Result: {"ok":true,"result":…} or {"ok":false,"error":…} |
registerCallback(type, name, handler) | set:callback (token, login) — answer with respond.resolve(json) or reject(error), within 10s. event:on / event:once, any event or * |
removeCallback(type, name) | undo registerCallback, same type |
Handlers run on the main thread. The full command list is in the Widget API.
Attaching files
The chat's attach button is an <input type="file">. An Android WebView does nothing when it is tapped unless the app implements WebChromeClient.onShowFileChooser — no picker, no error, no log. That is why most WebView wrappers carry a file-chooser handler.
PleasedWebViewSetup implements it: it opens the system picker for the types the widget accepts and hands the chosen file back to the page. Your part is forwarding onActivityResult, shown in Step 3. No extra permission is needed — the system picker grants access to the one file the visitor chooses.
If you install your own WebChromeClient after configure(), it replaces ours, and you must implement onShowFileChooser yourself — always answering the callback, with null on cancel, or the attach button stays dead until the page reloads.
On iOS, WKWebView shows its own picker; the only addition is NSCameraUsageDescription — see iOS: Attaching files.
Voice calls and the microphone
PleasedWebViewSetup handles the permission itself — the only other piece is the settings handler in Step 4, explained below. What it does, and why:
It answers onPermissionRequest. Not overriding that method is not a neutral choice: the default implementation denies, with no prompt shown and nothing logged. The chatbot then reports a refusal it cannot tell apart from the visitor saying no.
It does not compare request.origin to your page's URL. That origin is the widget's own iframe, not the page you loaded, so comparing them refuses every correctly-working integration. If you write your own handler, this is the mistake to avoid.
It grants audio only, never video, and it refuses any request whose origin it cannot identify.
It keeps the WebView on the page you loaded — off-site links open in the browser instead, where they cannot reach your token callback. The page is pinned once its first load finishes, so a redirect on the way in is fine; after that, a different URL is off-limits. Fragments are ignored, since they never load anything.
When the microphone is blocked
After a visitor refuses the microphone twice, Android stops asking: every later request is refused at once, with no prompt. Nothing the page does can undo that — only your app can open the settings screen where the visitor can. So when a call needs the microphone and it is blocked, the widget asks your app to, with the request_open_settings event, and your app opens its own settings page. That is the handler in Step 4.
canOpenAppSettings tells the widget you have that handler. With it, the visitor sees "Microphone access is blocked for this app" and an Open settings button; when they come back from settings the widget checks again and the call starts by itself. Without it, the widget cannot offer a way back and shows "Calls aren't available on this device" with only other ways to reach you.
Declare it only if you registered the handler — a button that does nothing is worse than no button. And do not open settings yourself from onPermissionRequest: the visitor lands in a system screen mid-tap with nothing explaining why, and the widget loses the chance to tell them. PleasedWebViewSetup refuses and stops there on purpose.
If you self-host the loader
The microphone is granted to your page and to cdn.pleased.com, because the widget asks from its own iframe. Add wherever you serve it from to that set:
kotlin
PleasedWebViewSetup(
this,
webView,
widgetOrigins = PleasedWebViewSetup.DEFAULT_WIDGET_ORIGINS + "https://chat.yourdomain.com",
)Add, not replace. A bare setOf("https://chat.yourdomain.com") becomes the whole list and drops cdn.pleased.com — and the iframe the widget runs in is a build-time URL that self-hosting the loader script does not move, so it still asks from there. The microphone is then denied on every voice call, with no prompt, looking exactly like the visitor said no.
Wrapping the page in another iframe
If the host page sits inside an iframe of your own, that iframe must carry allow="microphone":
html
<iframe src="https://cdn.pleased.com/widget/native/index.html?clientId=…" allow="microphone"></iframe>Without it the browser blocks the request before your app is ever consulted — your code will still run, still grant, still log success, and the microphone will still fail.
Checklist
| Symptom | Cause |
|---|---|
"Webpage not available", net::ERR_CACHE_MISS | INTERNET missing from the manifest |
| Widget never appears | Check clientId and widgetId, and that the page is served over HTTPS |
onLoaderReady never fires | pl-native.js loaded before the loader, or an injected loader with no onload |
| The visitor's name is missing; they are treated as a guest | The token callback is not registered, or returns "" |
| Two chat bubbles, or a bubble over your own UI | platform=app missing from the URL |
| Blank screen after the visitor minimises the chat | The close event is not handled — with platform=app there is no bubble |
| Microphone prompt appears, Allow does nothing | onRequestPermissionsResult not forwarded |
| Attach button does nothing | No onShowFileChooser — your own WebChromeClient replaced ours |
| File picker opens, nothing is attached | onActivityResult not forwarded |
| "Calls aren't available on this device", no button | canOpenAppSettings not declared, or no request_open_settings handler |
NotReadableError — Could not start audio source | MODIFY_AUDIO_SETTINGS missing from the manifest |
NotAllowedError with no prompt at all | No onPermissionRequest handler, or an iframe without allow="microphone" |
| Nothing plays back | mediaPlaybackRequiresUserGesture left at its default |
Inspect the page from desktop Chrome at chrome://inspect while the app runs — the widget's own console output is the fastest way to tell these apart.