fix(android): skip eval on a destroyed WebView
Closes #8562
Description
Bridge.eval() and MockCordovaWebViewImpl.eval() post evaluateJavascript to the main looper without checking whether the WebView is still alive. When the activity is recreated, evals queued during teardown (e.g. the Cordova document pause event) run after webView.destroy() and log cr_AwContents: Application attempted to call on a destroyed WebView.
This adds a volatile destroyed flag to both classes and checks it inside the posted runnable:
Bridge: set inonDetachedFromWindow()right beforewebView.destroy()MockCordovaWebViewImpl: set at the start ofhandleDestroy(), before theisInitialized()early return, so it is set even when Cordova was never initialized
Change Type
- Fix
- Feature
- Refactor
- Breaking Change
- Documentation
- Other (CI, chores, etc.)
Rationale / Problems Fixed
Only evals aimed at a JS context that is already being torn down are dropped; they could not run anyway. Events delivered through the plugin message channel are unaffected, e.g. the outgoing page still receives its final appStateChange (isActive=false) before teardown.
Tests or Reproductions
Stock app from npm init @capacitor/app + @capacitor/app, default android:configChanges, logging lifecycle events (appStateChange, App pause/resume, document pause/resume) to logcat. Activity recreated 10 times via adb shell settings put system font_scale 1.15 / 1.0.
Device: Android Emulator (sdk_gphone64_arm64), Android 17 (API 37), WebView 157.0.8103.50. The issue was reported on Android 14; the race is in Capacitor's own teardown order, so it is not version-specific.
@capacitor/android8.6.2 from npm: 10/10 recreates loggedApplication attempted to call on a destroyed WebView, each ~15–20 ms afterApp destroyed- With this patch (
@capacitor/androidlinked to this branch): 0/10, and every recreate still ends withApp startedand a fresh page load - Background/foreground without recreate (Home, then reopen):
document pause,pause,appStateChange isActive=false, thenappStateChange isActive=true,resume,document resumeare all delivered to the same page, soeval()works normally while the WebView is alive npm run verify(inandroid/) passes
Screenshots / Media
N/A
Platforms Affected
- Android
- iOS
- Web
Notes / Comments
Unrelated to this fix but visible in the same logs: after a recreate the new page registers its appStateChange listener after the native side has already notified (No listeners found for event appStateChange), so the new page does not receive an initial isActive=true. That is existing behaviour and is not changed here.
No unit test included: the library's unit tests don't cover the bridge lifecycle, and this needs a real WebView. Happy to add one if you can point me to a preferred approach.