By Rahul — Google Frontend Engineer
Why This Matters
Many apps embed web content inside native apps using WebView. The web page needs to talk to the native app (access camera, GPS, file system) and the native app needs to send data to the web page. Getting this communication right is critical for hybrid apps.
JavaScript Bridge (Android)
Android's WebView lets you inject a JavaScript interface:
WKScriptMessageHandler (iOS)
URL Scheme Interception
The oldest and most universal method. Web page navigates to a custom URL, native app intercepts it:
postMessage Pattern
Production Best Practices
- Always check if the bridge exists:
if (window.Android)before calling - Use a message queue for async responses — match request/response with IDs
- Validate all data coming from the bridge — never trust it blindly
- Version your bridge API — old app versions may not have new methods
- Handle the case where the page runs outside WebView (regular browser)
Security Concerns
- JavaScript bridges expose native functionality to web content — restrict which URLs can use the bridge
- Never expose sensitive methods (file access, contacts) without user confirmation
- On Android,
@JavascriptInterfacemethods are accessible to any JS on the page, including injected scripts
Summary
WebView-native communication uses JavaScript bridges (Android), message handlers (iOS), URL scheme interception, or postMessage. Always version your bridge API, validate data, and handle the non-WebView case gracefully.