ClinicKit Mobile SDK

Communication with BrowserCall UI

The VSee Clinic mobile apps embed the browser call in a web view (WKWebView on iOS, WebView on Android). This page explains how the native app and the web page talk to each other, and lists the events the browser sends to the app.

How it works

The web page and the native code each expose a function the other side can call. This lets the two sides exchange data and trigger actions, for example telling the app that the provider joined or that the visit ended.

iOS

To receive messages from the web page in native code, use the WKScriptMessageHandler protocol. Set up a message handler in native code and register it with the WKWebView:

  1. Create a class that implements WKScriptMessageHandler, and handle incoming messages in its userContentController(_:didReceive:) method.
  2. Create an instance of the class and add it to a WKUserContentController.
  3. Set the userContentController property of a WKWebViewConfiguration to that WKUserContentController.
  4. Create the WKWebView with that WKWebViewConfiguration.
class MessageHandler: NSObject, WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "myMessageHandler" {
            // Handle the message here
        }
    }
}

let messageHandler = MessageHandler()

let userContentController = WKUserContentController()
userContentController.add(messageHandler, name: "myMessageHandler")

let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController

let webView = WKWebView(frame: .zero, configuration: configuration)

Android

Create an interface between JavaScript and your Android code. JavaScript calls a method on the interface to send a String of content to the app.

  1. Create a Kotlin class that acts as the interface between JavaScript and the app. Add @JavascriptInterface to the methods JavaScript can call.
    class WebAppJSInterface {
    
        /** VseeApp uses ObjectMapper for JSON serialization and deserialization */
        private val objectMapper = ObjectMapper().apply {
            registerModule(KotlinModule())
            configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT)
            enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
        }
    
        /** Handle the different types of events from the web page */
        @JavascriptInterface
        fun postMessage(content: String) {
            try {
                val event: JsEvent = objectMapper.readValue(content, JsEvent::class.java)
                Timber.d("Received JS event: ${event.name}")
                Timber.d("Content: ${event.data}")
            } catch (e: JsonParseException) {
                Timber.e(e, "Error parsing message from JS")
            } catch (e: JsonMappingException) {
                Timber.e(e, "Error mapping JsEvent data structure")
            }
        }
    }
  2. Call addJavascriptInterface() with an instance of that class and the name JavaScript will use to reach it.
    webview.addJavascriptInterface(WebAppJSInterface(), "VseeAndroid")
    webview.loadUrl(args.url)

This creates an interface called VseeAndroid for JavaScript running in the WebView. The web page now has access to the WebAppJSInterface class.

JavaScript

To send a message from the web page to the iOS app:

  1. Build a message with the data you want to send to native code.
  2. Send it through window.webkit.messageHandlers, using the name of the message handler you registered.
window.webkit.messageHandlers.myMessageHandler.postMessage({ data: 'Hello, native code!' });

In VSee Clinic, the browser call does this in /js/mobile_app_bridge.js. It detects whether it runs inside the iOS app, the Android app or a normal browser, and forwards call events to the app:

define(['lodash', 'knockout'], function (_, ko) {
	var mobile_app_bridge = {
		send_message_to_ios: function(message) {
			if (typeof window.webkit !== 'undefined' && typeof window.webkit.messageHandlers !== 'undefined') {
				console.log("Opened in an iOS app");
				console.log(message);
				webkit.messageHandlers.visitDetailObject.postMessage(message);
			} else if (VseeAndroid != 'undefined') {
				console.log("Send message to Android");
				console.log(message);
				VseeAndroid.postMessage(JSON.stringify(message));
			}
			else {
				// Web page is likely opened in a web browser
				console.log("Opened in a web browser");
			}
		},
		receive_message_from_ios: function(message) {
			console.log('Received message from app:', message);
			// Handle the received message from app
		},
		get_visit: function () {
			if (typeof window.VisitVM === 'object' && typeof window.VisitVM.visit === 'function' && window.VisitVM.visit().id) {
				return window.VisitVM.visit();
			}
			if (typeof window.currentVisitVM === 'object' && typeof window.currentVisitVM.visit === 'function' && window.currentVisitVM.visit().id) {
				return window.currentVisitVM.visit();
			}
			if (typeof window.viewingVisit === 'object' && window.viewingVisit.id) {
				return window.viewingVisit;
			}
			return null;
		}
	};

	ko.postbox.subscribe('patient.inbrowserCalling.ParticipantJoined', function(data) {
		mobile_app_bridge.send_message_to_ios({
			name: 'provider_joined',
			data: {
				user_count: data.userCount
			}
		});
	});

	ko.postbox.subscribe('conference.ParticipantLeft', function(data) {
		console.log("participant left");
		var visit_info = mobile_app_bridge.get_visit();
		var activeParticipants = data.activeParticipants;
		console.log(data);
		if (activeParticipants.length < 2 && visit_info.status == CONST.VISIT.STATUS.COMPLETED || visit_info.status == CONST.VISIT.STATUS.DELETED) {
			mobile_app_bridge.send_message_to_ios({
				name: 'visit_ended',
				data: {
					visit: visit_info
				}
			});
		}
	});
});

Events from the browser to the app

The browser sends these events through the visitDetailObject message handler.

host_joined

Sent when the provider joins the call. Triggered by patient.inbrowserCalling.ParticipantJoined.

{
  "name": "host_joined",
  "data": {
    "userCount": 2,
    "isCurrentParticipant": false,
    "vseeId": "xxxx@xxx"
  }
}

visit.ended

Sent when the visit ends. When the provider checks the patient out, the server sends the visits.hangup.patient notification to the patient side, which hangs up the call.

{
  "name": "visit.ended",
  "data": {
    "id": "1000350986",
    "status": "completed",
    "status_updated_by": "10001"
  }
}

References