feat(android): allow scoping WebView bridge origin policy
What
Apps using server.url often list additional hosts in server.allowNavigation (such as OAuth providers or marketing pages) so top-level flows stay inside the WebView instead of opening the system browser.
Today on Android, Bridge.setAllowedOriginRules() feeds every server.allowNavigation entry into MessageHandler's WebViewCompat.addWebMessageListener(...) registration, and MessageHandler falls back to webView.addJavascriptInterface(this, "androidBridge") if WEB_MESSAGE_LISTENER is unavailable or registration fails. CapacitorCookies.load() also unconditionally attaches CapacitorCookiesAndroidInterface via addJavascriptInterface, which has no caller-origin or frame check.
This adds an opt-in Bridge.Builder.setWebMessagePolicy(...) hook (MessageHandler.WebMessagePolicy) so Android host apps can scope native bridge access to a narrower set of trusted origins than server.allowNavigation without changing default behavior for existing apps:
- Allows
BridgeActivity/Bridge.Buildercallers to supply aMessageHandler.WebMessagePolicywith explicitWebMessageListeneroriginRulesand a runtimesourceOriginpredicate (acceptsOrigin). - Updates
javaScriptReplyProxybefore dispatching accepted main-frame messages. - Fails closed when
scopedWebMessagesis configured: skips registeringaddJavascriptInterface(this, "androidBridge")and skipsevaluateJavascriptlegacy responses whenWEB_MESSAGE_LISTENERis unavailable or listener registration fails. - Skips registering
CapacitorCookiesAndroidInterfaceinCapacitorCookies.load()whenbridge.hasScopedWebMessages()is enabled (native-bridge.tsalready guardstypeof win.CapacitorCookiesAndroidInterface !== 'undefined').
Verification
- Added unit tests in
MessageHandlerTestandCapacitorCookiesTestcovering trusted main-frame dispatch, subframe/untrusted/null-origin rejection, fail-closed handling whenWEB_MESSAGE_LISTENERis unsupported or throws, empty origin rules, andCapacitorCookiesAndroidInterfaceregistration gating. - Ran
npm run eslintandnpm run prettier -- --check(0 errors). - Ran
npm run verify -w android(./gradlew clean lint build test -b capacitor/build.gradleon JDK 21): Android Lint found no new issues, and bothtestDebugUnitTestandtestReleaseUnitTestpass.