Skip to content

Integrating the Chatbot into an iOS App ​

This guide covers putting the Pleased chatbot inside an iOS app, in a WKWebView.

It assumes you have already done Getting Started and have your data-pls-client-id and data-pls-widget-id.

For Android, see Android Integration.

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 WKWebView 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:

two Info.plist entriesthe microphone for voice, the camera for photo attachments
two Swift filesWebView setup, and a bridge for driving the widget from your app
a URLthe page your WKWebView loads

Deployment target iOS 15 or higher. PleasedWebViewSetup.swift uses the iOS 15 microphone hook (WKUIDelegate.requestMediaCapturePermissionFor) and does not compile for anything lower. Nothing else is required — no CocoaPods, no SPM packages.

Step 1: Add the usage descriptions ​

Add both to Info.plist (or the target's Info tab in Xcode):

xml
<key>NSMicrophoneUsageDescription</key>
<string>We use the microphone for voice support in the chat.</string>
<key>NSCameraUsageDescription</key>
<string>We use the camera so you can send a photo in the chat.</string>

iOS shows these on its permission prompts.

NSCameraUsageDescription is not optional

The chat's attach button accepts images, so on a real iPhone the system picker offers Take Photo. Tapping it without this key crashes the app. The Simulator has no camera and never shows that option, so testing there will not catch it.

Without NSMicrophoneUsageDescription, microphone requests are refused and no prompt appears. Skip that one only if you are certain you will never enable voice calls.

Step 2: Add the two Swift files ​

Copy these into your project. They use framework API only — no third-party libraries.

PleasedWebViewSetup.swift ​

Configures the WKWebView and answers microphone requests (iOS 15+).

swift
import Foundation
import SafariServices
import UIKit
import WebKit

/// WebView setup for the Pleased chatbot. Copy this file as-is.
final class PleasedWebViewSetup: NSObject {
    static let defaultWidgetOrigins: Set<String> = ["https://cdn.pleased.com"]

    private weak var webView: WKWebView?
    private let widgetOrigins: Set<String>
    private var pinnedUrl: String?

    init(webView: WKWebView, widgetOrigins: Set<String> = PleasedWebViewSetup.defaultWidgetOrigins) {
        self.webView = webView
        self.widgetOrigins = widgetOrigins
        super.init()
    }

    /// Apply before `WKWebView(frame:configuration:)`. Playback options are read at construction.
    static func applyMediaPlaybackPolicy(to configuration: WKWebViewConfiguration) {
        configuration.allowsInlineMediaPlayback = true
        if #available(iOS 10.0, *) {
            configuration.mediaTypesRequiringUserActionForPlayback = []
        }
        if #available(iOS 16.4, *) {
            configuration.preferences.isElementFullscreenEnabled = true
        }
    }

    func configure() {
        guard let webView else { return }
        #if DEBUG
        if #available(iOS 16.4, *) {
            webView.isInspectable = true
        }
        #endif

        webView.navigationDelegate = self
        webView.uiDelegate = self
    }

    static func origin(of urlString: String?) -> String? {
        guard let urlString,
              let url = URL(string: urlString),
              let scheme = url.scheme,
              let host = url.host
        else { return nil }
        if let port = url.port {
            return "\(scheme)://\(host):\(port)"
        }
        return "\(scheme)://\(host)"
    }

    private func withoutFragment(_ url: String) -> String {
        url.split(separator: "#", maxSplits: 1).first.map(String.init) ?? url
    }

    private func leaveWebView(_ url: String) {
        guard let url = URL(string: url) else { return }
        DispatchQueue.main.async {
            UIApplication.shared.open(url)
        }
    }

    func answerMediaCapture(
        origin: WKSecurityOrigin,
        type: WKMediaCaptureType,
        decisionHandler: @escaping (WKPermissionDecision) -> Void
    ) {
        guard type == .microphone else {
            decisionHandler(.deny)
            return
        }
        let asking = Self.origin(from: origin)
        let pinnedOrigin = Self.origin(of: pinnedUrl)
        if asking == nil || (asking != pinnedOrigin && !widgetOrigins.contains(asking ?? "")) {
            decisionHandler(.deny)
            return
        }
        decisionHandler(.grant)
    }

    static func origin(from securityOrigin: WKSecurityOrigin) -> String? {
        let host = securityOrigin.host
        if host.isEmpty { return nil }
        if securityOrigin.port == 0 {
            return "\(securityOrigin.protocol)://\(host)"
        }
        return "\(securityOrigin.protocol)://\(host):\(securityOrigin.port)"
    }
}

extension PleasedWebViewSetup: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if pinnedUrl == nil {
            pinnedUrl = withoutFragment(webView.url?.absoluteString ?? "")
        }
    }

    func webView(
        _ webView: WKWebView,
        decidePolicyFor navigationAction: WKNavigationAction,
        decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
    ) {
        // target="_blank" / window.open: no target frame and we do not implement createWebView — open Safari.
        if navigationAction.targetFrame == nil {
            if let target = navigationAction.request.url?.absoluteString {
                leaveWebView(target)
            }
            decisionHandler(.cancel)
            return
        }
        guard navigationAction.targetFrame?.isMainFrame == true else {
            decisionHandler(.allow)
            return
        }
        let pinned = pinnedUrl
        guard let pinned, let target = navigationAction.request.url?.absoluteString else {
            decisionHandler(.allow)
            return
        }
        if withoutFragment(target) == pinned {
            decisionHandler(.allow)
            return
        }
        leaveWebView(target)
        decisionHandler(.cancel)
    }

    func webView(
        _ webView: WKWebView,
        decidePolicyFor navigationResponse: WKNavigationResponse,
        decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void
    ) {
        guard navigationResponse.isForMainFrame else {
            decisionHandler(.allow)
            return
        }
        let pinned = pinnedUrl
        guard let pinned, let target = navigationResponse.response.url?.absoluteString else {
            decisionHandler(.allow)
            return
        }
        if withoutFragment(target) == pinned {
            decisionHandler(.allow)
            return
        }
        leaveWebView(target)
        decisionHandler(.cancel)
    }
}

@available(iOS 15.0, *)
extension PleasedWebViewSetup: WKUIDelegate {
    func webView(
        _ webView: WKWebView,
        requestMediaCapturePermissionFor origin: WKSecurityOrigin,
        initiatedByFrame frame: WKFrameInfo,
        type: WKMediaCaptureType,
        decisionHandler: @escaping (WKPermissionDecision) -> Void
    ) {
        answerMediaCapture(origin: origin, type: type, decisionHandler: decisionHandler)
    }
}

PleasedBridge.swift ​

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.

swift
import Foundation
import WebKit

/// Drives the Pleased loader running inside a WKWebView. Copy this file as-is.
final class PleasedBridge: NSObject {
    typealias CallbackHandler = (_ payloadJson: String?, _ respond: Responder) -> Void

    protocol Responder: AnyObject {
        func resolve(valueJson: String?)
        func reject(error: String)
    }

    var onLoaderReady: (() -> Void)?
    var onLog: ((String) -> Void)?

    private weak var webView: WKWebView?
    private weak var userContentController: WKUserContentController?
    private let lock = NSLock()
    private var handlers: [String: CallbackHandler] = [:]

    /// Attach before creating the WKWebView so `pleasedNative` exists when the page loads.
    init(configuration: WKWebViewConfiguration) {
        super.init()
        let controller = configuration.userContentController
        userContentController = controller
        controller.add(self, name: "pleasedNative")
    }

    func bind(webView: WKWebView) {
        self.webView = webView
    }

    deinit {
        userContentController?.removeScriptMessageHandler(forName: "pleasedNative")
    }

    func invoke(_ command: String, payloadJson: String? = nil, onResult: ((String) -> Void)? = nil) {
        if let payloadJson, !payloadJson.isEmpty {
            // Match JSONTokener on Android: allow null and other JSON fragments, not only objects/arrays.
            let opts: JSONSerialization.ReadingOptions = [.fragmentsAllowed]
            if (try? JSONSerialization.jsonObject(with: Data(payloadJson.utf8), options: opts)) == nil {
                let error = #"{"ok":false,"error":"payloadJson is not valid JSON"}"#
                dispatchMain { onResult?(error) }
                return
            }
        }
        let payloadPart = payloadJson.map { jsonQuote($0) } ?? "null"
        let js = "window.__plInvoke(\(jsonQuote(command)), \(payloadPart))"
        eval(js, onResult: onResult)
    }

    func registerCallback(type: String, name: String, handler: @escaping CallbackHandler) {
        lock.lock()
        handlers["\(type)|\(name)"] = handler
        lock.unlock()
        eval("window.__plAddCallback(\(jsonQuote(type)), \(jsonQuote(name)))")
    }

    func removeCallback(type: String, name: String) {
        lock.lock()
        handlers.removeValue(forKey: "\(type)|\(name)")
        lock.unlock()
        eval("window.__plRemoveCallback(\(jsonQuote(type)), \(jsonQuote(name)))")
    }

    private func eval(_ js: String, onResult: ((String) -> Void)? = nil) {
        dispatchMain {
            guard let webView = self.webView else {
                onResult?("null")
                return
            }
            // Same transport as Android: evaluateJavaScript. callAsyncJavaScript often returns
            // a parsed object or a differently-encoded string, which broke invoke callbacks.
            webView.evaluateJavaScript(js) { value, error in
                if error != nil, onResult != nil {
                    onResult?("null")
                    return
                }
                if let onResult {
                    onResult(Self.unwrap(value))
                }
            }
        }
    }

    private func dispatchMain(_ block: @escaping () -> Void) {
        if Thread.isMainThread {
            block()
        } else {
            DispatchQueue.main.async(execute: block)
        }
    }

    /**
     * evaluateJavascript JSON-encodes what the page returned, and the shim returns a JSON
     * string — so results can arrive double-encoded. Undo one layer, matching PleasedBridge.kt.
     */
    private static func unwrap(_ value: Any?) -> String {
        guard let value else { return "null" }

        if let str = value as? String {
            return peelJsonStringIfNeeded(str)
        }
        if let str = value as? NSString {
            return peelJsonStringIfNeeded(str as String)
        }
        if JSONSerialization.isValidJSONObject(value),
           let data = try? JSONSerialization.data(withJSONObject: value),
           let json = String(data: data, encoding: .utf8) {
            return json
        }
        if let num = value as? NSNumber {
            return num.stringValue
        }
        return "null"
    }

    private static func peelJsonStringIfNeeded(_ value: String) -> String {
        guard let data = value.data(using: .utf8),
              let parsed = try? JSONSerialization.jsonObject(with: data)
        else {
            return value
        }
        if let inner = parsed as? String {
            return inner
        }
        return value
    }

    private func jsonQuote(_ string: String) -> String {
        guard let data = try? JSONEncoder().encode(string),
              let encoded = String(data: data, encoding: .utf8)
        else {
            return "\"\""
        }
        return encoded
    }

    private func resolve(id: String, valueJson: String?) {
        let valuePart = valueJson.map { jsonQuote($0) } ?? "null"
        eval("window.__plResolveCallback(\(jsonQuote(id)), \(valuePart))")
    }

    private func reject(id: String, error: String) {
        eval("window.__plRejectCallback(\(jsonQuote(id)), \(jsonQuote(error)))")
    }

    private func onMain(_ block: @escaping () -> Void) {
        dispatchMain(block)
    }

    private final class JsResponder: Responder {
        private var settled = false
        private let id: String
        private weak var bridge: PleasedBridge?

        init(id: String, bridge: PleasedBridge) {
            self.id = id
            self.bridge = bridge
        }

        func resolve(valueJson: String?) {
            guard !settled else { return }
            settled = true
            bridge?.resolve(id: id, valueJson: valueJson)
        }

        func reject(error: String) {
            guard !settled else { return }
            settled = true
            bridge?.reject(id: id, error: error)
        }
    }

    private final class NoopResponder: Responder {
        static let shared = NoopResponder()
        func resolve(valueJson: String?) {}
        func reject(error: String) {}
    }
}

extension PleasedBridge: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        guard message.name == "pleasedNative",
              let body = message.body as? String,
              let data = body.data(using: .utf8),
              let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
              let kind = json["kind"] as? String
        else { return }

        switch kind {
        case "loader_ready":
            onMain { self.onLoaderReady?() }

        case "log":
            if let text = json["message"] as? String {
                onMain { self.onLog?(text) }
            }

        case "event":
            let name = json["name"] as? String ?? ""
            let via = json["via"] as? String ?? ""
            let wildcard = json["wildcard"] as? Bool ?? false
            let payloadString = Self.jsonPayloadString(from: json["payload"])

            if wildcard {
                var envelope: [String: Any] = ["event": name]
                envelope["payload"] = json["payload"] ?? NSNull()
                let envelopeJson = (try? JSONSerialization.data(withJSONObject: envelope))
                    .flatMap { String(data: $0, encoding: .utf8) }
                onMain {
                    if let handler = self.handler(for: "\(via)|*") {
                        handler(envelopeJson, NoopResponder.shared)
                    }
                }
            } else if via.isEmpty {
                onMain {
                    if let handler = self.handler(for: "event:on|\(name)") {
                        handler(payloadString, NoopResponder.shared)
                    }
                    if let handler = self.handler(for: "event:once|\(name)") {
                        handler(payloadString, NoopResponder.shared)
                    }
                }
            } else {
                onMain {
                    if let handler = self.handler(for: "\(via)|\(name)") {
                        handler(payloadString, NoopResponder.shared)
                    }
                }
            }

        case "callback":
            let name = json["name"] as? String ?? ""
            let id = json["id"] as? String ?? ""
            let type = json["type"] as? String ?? ""
            let payloadString = Self.jsonPayloadString(from: json["payload"])
            guard let handler = handler(for: "\(type)|\(name)") else {
                reject(id: id, error: "no handler registered for \(name)")
                return
            }
            onMain {
                handler(payloadString, JsResponder(id: id, bridge: self))
            }

        default:
            break
        }
    }

    private func handler(for key: String) -> CallbackHandler? {
        lock.lock()
        defer { lock.unlock() }
        return handlers[key]
    }

    /// Wire payloads as JSON strings for native handlers, matching Android's JSONObject string form.
    static func jsonPayloadString(from raw: Any?) -> String? {
        guard let raw, !(raw is NSNull) else { return nil }
        if let str = raw as? String { return str }
        if JSONSerialization.isValidJSONObject(raw),
           let data = try? JSONSerialization.data(withJSONObject: raw),
           let str = String(data: data, encoding: .utf8) {
            return str
        }
        return nil
    }
}

Step 3: Load the page ​

Apply playback settings on the WKWebViewConfiguration before you create the WKWebView.

This much displays the chatbot with no native bridge. Step 4 adds PleasedBridge on that same configuration (before the web view) and drives the widget — token, open/close, events.

swift
import UIKit
import WebKit

final class ChatViewController: UIViewController {
    private var webView: WKWebView!
    private var pleased: PleasedWebViewSetup!

    override func viewDidLoad() {
        super.viewDidLoad()

        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences.allowsContentJavaScript = true
        PleasedWebViewSetup.applyMediaPlaybackPolicy(to: config)

        webView = WKWebView(frame: view.bounds, configuration: config)
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(webView)

        pleased = PleasedWebViewSetup(webView: webView)
        pleased.configure()

        let url = URL(string:
            "https://cdn.pleased.com/widget/native/index.html" +
            "?clientId=YOUR_CLIENT_ID&widgetId=YOUR_WIDGET_ID&platform=ios"
        )!
        webView.load(URLRequest(url: url))
    }
}

A few things worth knowing:

  • platform=ios matters. It tells the widget your app owns the launcher, so it does not draw its own bubble over your UI. Use app on Android.
  • 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 close and hides, and what happens next is yours to decide. Handle it or the visitor is left staring at an empty WKWebView. Step 4 shows the handler.
  • Keep the PleasedWebViewSetup instance. It holds navigation and permission state. One instance per WKWebView.
  • applyMediaPlaybackPolicy(to:) must run on the configuration before WKWebView(...) is created. Inline playback and autoplay for call audio are fixed at construction; changing them on an existing web view is unreliable.
  • File attachments need no extra code, only the camera key from Step 1. WKWebView shows the system picker on its own. There is no Android-style onShowFileChooser equivalent.

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="ios"
></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 PleasedBridge with the same WKWebViewConfiguration before WKWebView(...) — the page looks for the message handler as soon as it runs.

This is Step 3's view controller with the bridge added, complete. It replaces the one above rather than being appended to it:

swift
import UIKit
import WebKit

final class ChatViewController: UIViewController {
    private var webView: WKWebView!
    private var pleased: PleasedWebViewSetup!
    private var bridge: PleasedBridge!

    override func viewDidLoad() {
        super.viewDidLoad()

        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences.allowsContentJavaScript = true
        PleasedWebViewSetup.applyMediaPlaybackPolicy(to: config)

        bridge = PleasedBridge(configuration: config)

        webView = WKWebView(frame: view.bounds, configuration: config)
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(webView)

        bridge.bind(webView: webView)

        bridge.onLoaderReady = { [weak self, weak bridge] in
            guard let bridge else { return }

            bridge.registerCallback(type: "set:callback", name: "token") { _, respond in
                fetchTokenFromYourBackend { token in
                    // Guest: resolve with an empty JSON string. Signed in: a JSON-encoded JWE string.
                    let quoted = (try? JSONEncoder().encode(token))
                        .flatMap { String(data: $0, encoding: .utf8) } ?? #""""#
                    respond.resolve(valueJson: quoted)
                }
            }

            // Each handler is stored on the bridge, so each captures self and bridge weakly.
            // See "Avoid retain cycles" below.
            bridge.registerCallback(type: "event:on", name: "ready") { [weak bridge] _, _ in
                bridge?.invoke("widget:open", payloadJson: "{}")
            }

            bridge.registerCallback(type: "event:on", name: "close") { [weak self] _, _ in
                self?.dismiss(animated: true)
            }

            bridge.registerCallback(type: "event:on", name: "request_open_settings") { _, _ in
                if let url = URL(string: UIApplication.openSettingsURLString) {
                    UIApplication.shared.open(url)
                }
            }
            bridge.invoke(
                "set:config",
                payloadJson: #"{"capabilities":{"canOpenAppSettings":true}}"#
            )
        }

        pleased = PleasedWebViewSetup(webView: webView)
        pleased.configure()

        let url = URL(string:
            "https://cdn.pleased.com/widget/native/index.html" +
            "?clientId=YOUR_CLIENT_ID&widgetId=YOUR_WIDGET_ID&platform=ios"
        )!
        webView.load(URLRequest(url: url))
    }
}

Closing the chat ​

platform=ios 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 WKWebView:

Where the chat livesOn close
A modal you presented, as abovedismiss — back to the screen that opened it
Inside a screen you already havehide the WKWebView, show your own entry point

Either way it is your code. Reopening later is bridge.invoke("widget:open", payloadJson: "{}"), or a fresh presentation — the widget does not remember it was closed.

Read Widget Auth and Widget Token for the token itself — the iOS side only has to hand over whatever your backend produced.

Commands ​

Anything from the Widget API works, passed through as a string:

swift
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 in /* {"ok":true,"result":true} */ }

get: commands answer through the callback; the rest return null.

Events ​

swift
bridge.registerCallback(type: "event:on", name: "on_chat:start") { payload, _ in /* … */ }

Or subscribe to everything, including events added after you ship:

swift
bridge.registerCallback(type: "event:on", name: "*") { payload, _ in
    // payload is {"event":"ready","payload":null}
    print(payload ?? "")
}

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.

swift
bridge.removeCallback(type: "event:on", name: "on_chat:start")

bridge.removeCallback(type: "set:callback", name: "token") // guest until re-registered

One handler per type and name: registering event:on close again replaces the previous one.

See Widget Events for the list.

Bridge reference ​

PleasedBridgeUse for
init(configuration:)before WKWebView(...); registers the pleasedNative script handler
bind(webView:)after the web view exists
onLoaderReadyregister everything below; runs once the loader is up
invoke(_: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(valueJson:) 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.

Avoid retain cycles

PleasedBridge keeps onLoaderReady and every registered handler strongly, and your view controller keeps the bridge. A handler that captures self or bridge strongly keeps the chat screen and its WKWebView alive after it is dismissed, with the widget still running. That includes a strong reference made by guard let self in the enclosing onLoaderReady. Give every closure you hand the bridge its own [weak self] or [weak bridge], as Step 4 does.

Attaching files ​

The chat's attach button is an <input type="file">. On iOS, WKWebView shows the system picker with no extra delegate code — unlike Android, where you must forward onActivityResult.

The input accepts images, so on a real device the picker includes Take Photo. That option needs NSCameraUsageDescription from Step 1; without it, tapping it crashes the app.

Voice calls and the microphone ​

PleasedWebViewSetup handles capture permission itself — the only other piece is the settings handler in Step 4, explained below. What it does, and why:

It implements requestMediaCapturePermissionFor (iOS 15+). If you omit this delegate method, WebKit falls back to its own prompt. The snippet answers instead: it grants microphone requests from the page you loaded and denies everything else.

The origin it checks is your page's, not the widget's. On Android the request comes from the widget's own iframe. WebKit instead passes the delegate the top-level page's origin; the iframe's is only on frame.securityOrigin. So a page you host yourself needs no extra configuration here: its origin is the one the snippet already trusts.

It grants microphone capture only, and it refuses any request whose origin it cannot identify.

It keeps the web view on the page you loaded — off-site navigation opens in Safari instead, where it cannot reach your token callback. target="_blank" and window.open are included. The page is pinned once its first load finishes; redirects on the way in are fine.

When the microphone is blocked ​

After a visitor refuses the microphone, or turns it off in Settings, later requests may fail immediately. Only your app can open the settings screen where the visitor can re-enable access. 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 Settings → Your app. 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 can start. Without it, the widget cannot offer a way back: the visitor sees "Microphone access is blocked for this site. Allow it in your browser or phone settings, then try again." and a Try again button, and has to find your app in Settings on their own.

Declare it only if you registered the handler — a button that does nothing is worse than no button.

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.

Checklist ​

SymptomCause
Widget never appearsCheck clientId and widgetId, and that the page is served over HTTPS
onLoaderReady never firespl-native.js loaded before the loader, or bridge not attached before load
The visitor's name is missing; they are treated as a guestThe token callback is not registered, or returns ""
Two chat bubbles, or a bubble over your own UIplatform=ios missing from the URL
Blank screen after the visitor minimises the chatThe close event is not handled — with platform=ios there is no bubble
Microphone prompt never appearsNSMicrophoneUsageDescription missing from Info.plist
App crashes on Take Photo in the attach menuNSCameraUsageDescription missing from Info.plist
NotAllowedError with no prompt at allThe visitor denied it before (see above), your own requestMediaCapturePermissionFor denied it, or an iframe without allow
Attachments / links do nothingYour own WKNavigationDelegate replaced the snippet's, which sends target="_blank" links to Safari
"Microphone access is blocked for this site", no Open settings buttoncanOpenAppSettings not declared, or no request_open_settings handler
Nothing plays back during a callapplyMediaPlaybackPolicy not called before creating the WKWebView

On a debug build, inspect the page with Safari → Develop → [device] → [your app] while the app runs — the widget's console output is the fastest way to tell these apart.