A sample Android project demonstrating secure communication between WebView and native code using WebViewCompat.addWebMessageListener.
- Secure WebView-to-Native communication
- Origin whitelisting
- Promise-based JavaScript API
- Request/Response pattern with unique callback IDs
- Early script injection via
addDocumentStartJavaScript - Eight demo endpoints: ping, getDeviceInfo, getAppInfo, showToast, getPreference, setPreference, copyToClipboard, share
WebViewBridgeDemo/
├── app/
│ ├── src/main/
│ │ ├── java/com/example/webviewbridge/
│ │ │ └── MainActivity.kt # Native bridge implementation
│ │ ├── assets/
│ │ │ └── test_bridge.html # Demo web page
│ │ └── res/
│ │ └── layout/activity_main.xml
│ └── build.gradle.kts
├── ARTICLE.md # Full technical article
└── README.md
WebViewCompat.addWebMessageListener(
webView,
"NativeBridge", // JS object name
setOf("https://trusted.com") // Allowed origins
) { _, message, _, _, replyProxy ->
// Handle message and reply
replyProxy.postMessage(response)
}// The bridge is auto-injected
NativeBridge.onmessage = (event) => {
console.log(event.data); // Response from native
};
NativeBridge.postMessage('{"action":"ping"}');- Open the project in Android Studio
- Sync Gradle files
- Run on device/emulator (API 24+)
- Use
addDocumentStartJavaScriptto inject the bridge wrapper early — avoids race conditions with page scripts - Use
NativeBridge.onmessage— Notwindow.addEventListener("message", ...) - Use
NativeBridge.postMessage— Notwindow.postMessage()
See ARTICLE.md for the full technical article.
- Android Studio Hedgehog or later
- minSdk 24
- compileSdk 34
- AndroidX WebKit 1.9.0+