[Bug]: Android: a destroyed BridgeActivity can leave its WebView and page running
I maintainer di solito rispondono entro 2 giorni
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 3/5
- Tempo stimato
- 1-2 giorni
- Idoneità per principianti
- 72/100
Direzione di ricerca
Start in Bridge.onDestroy() and BridgeActivity.onDetachedFromWindow(), where the issue describes WebView destruction. Read the existing detach handling and verify the suggested behavior for an unattached WebView and one that detaches after activity destruction. Reproduce the two activity recreation cases from the linked reproduction; done means only the recreated page remains running and the WebView is not destroyed while attached.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Capacitor Version
💊 Capacitor Doctor 💊
Latest Dependencies:
@capacitor/cli: 8.6.0
@capacitor/core: 8.6.0
@capacitor/android: 8.6.0
@capacitor/ios: 8.6.0
Installed Dependencies:
@capacitor/ios: not installed
@capacitor/cli: 8.6.0
@capacitor/core: 8.6.0
@capacitor/android: 8.6.0
[success] Android looking great! 👌
Also seen on 9.0.0-beta.0. The code involved is the same from 5.0.0 to 9.0.0-beta.0.
Other API Details
npm --version: 11.11.0
node --version: v24.14.1
Android emulator, API 37 (Android System WebView 156.0.8078.47)
Platforms Affected
- iOS
- Android
- Web
Current Behavior
Bridge destroys its WebView only in onDetachedFromWindow(), which BridgeActivity.onDetachedFromWindow()
calls. Bridge.onDestroy() notifies the plugins but leaves the WebView alone.
Android does not always detach a destroyed activity's window (ActivityThread.handleDestroyActivity):
- The window was never added (
mWindowAddedfalse). This happens when the activity is recreated right
after the launch: for example, the font size changes in the first second, andfontScaleis not in the
template'sconfigChanges. Nothing is detached, soonDetachedFromWindow()never runs. (Logged: the WebView
is in no window whenonDestroy()runs.) - The window is preserved for the recreated activity (
mPreserveWindow). This happens with
Activity.recreate()while the activity is visible, which an app or a library may call. According to
ActivityRecord, the system also preserves the window on a relaunch for size-only changes, when those are not
inconfigChanges; we did not test that one. Only the content view is cleared and the window is handed over,
soonDetachedFromWindow()never runs either.
In both cases the old WebView is never destroyed, and a second page, from the recreated activity, runs next to
it. The old page is never released: three minutes later, chrome://inspect still listed it and evaluated in it. In
the reproduction its timers kept running, hidden, for about 60 seconds, after which they stopped. The page
remained in memory with whatever it held, and in our app it registered its own plugin listeners: we saw two
App.addListener('backButton') registrations.
We found it through its worst effect. Our app keeps its data in SQLite on the origin private file system, from a
worker. The old page's worker kept the database's access handles, and the new page's worker could not open it
(NoModificationAllowedError: ... Access Handles cannot be created if there is another open Access Handle). The
app never started until it was force-stopped. Anything a page holds exclusively, such as a Web Lock or an OPFS
access handle, would be hit the same way.
Results on the reproduction (API 37 emulator, Capacitor 8.6.0, unmodified Bridge):
| Scenario | Pages left running |
|---|---|
| font size changed 0.2–0.6 s after the launch | 2 (15 runs of 16) |
| font size changed 0.8 s after the launch | 1 (2 runs of 2) |
recreate() while the app is visible |
2 (8 runs of 8) |
| font size changed while the app is visible | 1 |
The window that hits case 1 depends on the device's speed.
Expected Behavior
When the activity is destroyed, its WebView is destroyed with it, and only the recreated activity's page runs.
Project Reproduction
https://github.com/fgaudo/capacitor-webview-leak
Additional Information
Steps (also in the repository's README):
- Install the app.
- Case 1:
adb shell settings put system font_scale 1.0, then launch the app and run
adb shell settings put system font_scale 1.30.2–0.6 s later. - Case 2: with the app visible,
adb shell am start -n com.example.webviewleak/.MainActivity --ez recreate true
(the reproduction'sMainActivitycallsrecreate()for that extra). adb logcat | grep "alive for": two page ids log every second, for about a minute.chrome://inspectlists
two pages, and keeps listing them.
Why it happens: the destruction was added in #672 ("Destroy webview on app exit"), in onDetachedFromWindow
because "you can't call destroy while it's still attached, so we need to wait for it", on the assumption that
"onDetachedFromWindow is called when the activity is destroyed". The two cases above are where that assumption
fails. (#7766 reported that Bridge.onDestroy() never destroys the WebView, for BridgeFragment, which was then
removed.) #8562 is related but different: the events that MockCordovaWebViewImpl.eval() posts during a
recreation run after the WebView is destroyed.
Suggested fix: keep that constraint, and wait for the WebView's own detach rather than the activity's window.
In Bridge.onDestroy(), destroy the WebView now if it is in no window (case 1), and otherwise when it leaves its
window (case 2: the content view is cleared; the usual case: the window is removed). The usual path is unchanged:
the WebView is destroyed at the same moment as today, and onDetachedFromWindow() then finds it destroyed.
The diff is against 8.6.0. Bridge.onDestroy() and onDetachedFromWindow() are the same on main today.
@@ -15,6 +15,7 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
+import android.view.View;
import android.webkit.ServiceWorkerClient;
import android.webkit.ServiceWorkerController;
import android.webkit.ValueCallback;
@@ -1404,6 +1405,26 @@
if (cordovaWebView != null) {
cordovaWebView.handleDestroy();
}
+
+ // onDetachedFromWindow does not always follow: not when the activity is destroyed before its window was added, nor
+ // when a recreated activity takes the window over. Destroy the WebView once it leaves the window, or now if it is not
+ // in one, or its page keeps running.
+ if (webView.isAttachedToWindow()) {
+ webView.addOnAttachStateChangeListener(
+ new View.OnAttachStateChangeListener() {
+ @Override
+ public void onViewAttachedToWindow(View view) {}
+
+ @Override
+ public void onViewDetachedFromWindow(View view) {
+ view.removeOnAttachStateChangeListener(this);
+ webView.destroy();
+ }
+ }
+ );
+ } else {
+ webView.destroy();
+ }
}
With temporary logs in this change, the three paths show up as expected. In case 1, onDestroy found the WebView
in no window and destroyed it at once, and onDetachedFromWindow() never came. In case 2, the WebView was in a
window, then detached and was destroyed, and onDetachedFromWindow() never came. In the usual path, the WebView
detached and was destroyed, then onDetachedFromWindow() came.
With this change applied to the reproduction's Bridge.java (API 37 emulator), each case left one page running:
the launch cases at 0.2–0.6 s, recreate() three times, a cold start, a font size change while visible and while
in the background, and leaving with the back button and launching again. Logcat showed no crash and no
"destroy() called while WebView is still attached" warning. One or two "Application attempted to call on a
destroyed WebView" warnings appear after a recreation: the document events that MockCordovaWebViewImpl.eval posts for the
old activity (#8562). Unmodified Capacitor logs the same warning on a font size change while the app is visible.
Until a fix is released, an app can do the same in its own activity:
override fun onDestroy() {
super.onDestroy()
val webView = bridge?.webView ?: return
if (!webView.isAttachedToWindow) return webView.destroy()
webView.addOnAttachStateChangeListener(
object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(view: View) {}
override fun onViewDetachedFromWindow(view: View) {
view.removeOnAttachStateChangeListener(this)
webView.destroy()
}
},
)
}
- Lingua principale
- TypeScript
- Stelle
- 17.1k
- Fork
- 1.3k
- Merge medio
- 2g 1h
- PR unite (30g)
- 32
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Nessun modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di ionic-team/capacitor
-
[Bug]: Plugin call after navigation can be answered before reply proxy is updatedForse già presa @MateStrysewske l’ha presa 56 giorni fa. Apertatriage
Difficoltà 2/5 1-3 ore Idoneità per principianti 84/100
ionic-team/capacitor#8616 ·
I maintainer di solito rispondono entro 2 giorni
-
[Bug]: SystemBars shrinks the WebView twice for the keyboard on Android 10 (API 29) when WebView >= 140 and viewport-fit=coverForse già presa @theproducer l’ha presa 18 giorni fa. Apertaneeds reply
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
ionic-team/capacitor#8601 · 2 commenti · 3 reazioni · 1 assegnatario ·
I maintainer di solito rispondono entro 2 giorni
-
help wanted
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
ionic-team/capacitor#8574 · 3 commenti ·
I maintainer di solito rispondono entro 2 giorni
-
SystemBars: safe area CSS injection throws "Cannot read properties of null" on startup (Android 16)Forse già presa @kttalley l’ha presa 47 giorni fa. Apertatriage
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
ionic-team/capacitor#8530 · 2 commenti ·
I maintainer di solito rispondono entro 2 giorni
-
fix(android): remove unchecked Java compilation warningsForse già presa Una pull request collegata a questa issue è aperta o già unita. Apertatriage
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
ionic-team/capacitor#8529 · 1 commento ·
I maintainer di solito rispondono entro 2 giorni
Tutte le issue di ionic-team/capacitor
Issue simili
-
community first-timers-only good first issue hacktoberfest help wanted low hanging fruit up-for-grabs
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 85/100
lingdojo/kana-dojo#34223 · 1 commento · 5 reazioni ·
I maintainer di solito rispondono entro 1 giorno
-
bug status: needs triage
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
mastra-ai/mastra#30587 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
area:web p2 product:business triage:active type:bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
cuadrao-ai/argus#2228 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 88/100
embedpdf/embed-pdf-viewer#1098 ·
I maintainer di solito rispondono entro 1 giorno
-
.Needs Triage .Team/Metabot Priority:P3 Type:Bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 73/100
metabase/metabase#87252 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno