[Bug]: Android: a destroyed BridgeActivity can leave its WebView and page running

Đang mở
#8,690 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 2 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức phù hợp với người mới
72/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
android, java
Lĩnh vực
backend, mobile

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

triage
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):

  1. The window was never added (mWindowAdded false). This happens when the activity is recreated right
    after the launch: for example, the font size changes in the first second, and fontScale is not in the
    template's configChanges. Nothing is detached, so onDetachedFromWindow() never runs. (Logged: the WebView
    is in no window when onDestroy() runs.)
  2. 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
    in configChanges; we did not test that one. Only the content view is cleared and the window is handed over,
    so onDetachedFromWindow() 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):

  1. Install the app.
  2. 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.3 0.2–0.6 s later.
  3. Case 2: with the app visible, adb shell am start -n com.example.webviewleak/.MainActivity --ez recreate true
    (the reproduction's MainActivity calls recreate() for that extra).
  4. adb logcat | grep "alive for": two page ids log every second, for about a minute. chrome://inspect lists
    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()
            }
        },
    )
}
Ngôn ngữ chính
TypeScript
Star
17.1k
Fork
1.3k
Merge trung bình
2 ngày 1 giờ
Pull request đã merge (30 ngày)
32

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của ionic-team/capacitor

Tất cả issue của ionic-team/capacitor

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.