WebView - Native Bridges

Last updated
July 3, 2025

Overview

When embedding the Saphere Scan widget inside a WebView (e.g., in React Native or Ionic), you may need to exchange data between the web page and the native code (Android/iOS).

React Native

Use react-native-webview and its onMessage and injectJavaScript APIs:

From WebView (JavaScript in HTML) to Native

window.ReactNativeWebView.postMessage(JSON.stringify({ type: "scanComplete", data: results }))

From Native (React Native) to WebView

webviewRef.current.injectJavaScript(`Handler.destroy();`);

In your React Native code, handle messages like so:

<WebView
  source={{ uri }}
  onMessage={({ nativeEvent: { data } }) => {
    const message = JSON.parse(data);
    console.log("Received from WebView:", message);
  }}
/>

Android (Native)

Use the addJavascriptInterface() method to expose a bridge:

webView.addJavascriptInterface(new MyJavascriptBridge(), "AndroidBridge");

In your HTML:

AndroidBridge.sendToNative(JSON.stringify({ type: "result", value: data }));

iOS (Native)

Use WKScriptMessageHandler with WKWebView:

userContentController.add(self, name: "iosBridge")

In JavaScript:

window.webkit.messageHandlers.iosBridge.postMessage({ type: 'done', result: result })

This allows structured, bi-directional communication between your native environment and the embedded scan widget.

Ionic

To exchange data in an Ionic application (especially when using Capacitor), you rely on WebView communication similar to React Native.

Communication from WebView to Native (Ionic/Capacitor)

Inside your embedded HTML:

window.dispatchEvent(new CustomEvent('saphere-result', { detail: { result: data } }));

In your Ionic/Capacitor app (TypeScript):

document.addEventListener('saphere-result', (event: any) => {
  console.log('Scan result:', event.detail.result);
});

Communication from Native to WebView

Use the Capacitor WebView plugin to execute JS inside the WebView:

import { WebView } from '@capacitor-community/webview';
WebView.evalJs("Handler.destroy();");

Tip: You can also inject JS on load or listen for native-side events to trigger cleanup or new scans from Ionic code.

Close Modal