@capacitor/android 9.0.0-rc.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
1
  ext {
2
- androidxActivityVersion = project.hasProperty('androidxActivityVersion') ? rootProject.ext.androidxActivityVersion : '1.13.0'
3
- androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.8.0'
4
- androidxCoordinatorLayoutVersion = project.hasProperty('androidxCoordinatorLayoutVersion') ? rootProject.ext.androidxCoordinatorLayoutVersion : '1.3.0'
5
- androidxCoreVersion = project.hasProperty('androidxCoreVersion') ? rootProject.ext.androidxCoreVersion : '1.19.1'
6
- androidxFragmentVersion = project.hasProperty('androidxFragmentVersion') ? rootProject.ext.androidxFragmentVersion : '1.9.1'
7
- androidxWebkitVersion = project.hasProperty('androidxWebkitVersion') ? rootProject.ext.androidxWebkitVersion : '1.17.1'
8
- junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
9
- androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0'
10
- androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0'
2
+ androidxActivityVersion = rootProject.hasProperty('androidxActivityVersion') ? rootProject.ext.androidxActivityVersion : '1.13.0'
3
+ androidxAppCompatVersion = rootProject.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.8.0'
4
+ androidxCoordinatorLayoutVersion = rootProject.hasProperty('androidxCoordinatorLayoutVersion') ? rootProject.ext.androidxCoordinatorLayoutVersion : '1.3.0'
5
+ androidxCoreVersion = rootProject.hasProperty('androidxCoreVersion') ? rootProject.ext.androidxCoreVersion : '1.19.1'
6
+ androidxFragmentVersion = rootProject.hasProperty('androidxFragmentVersion') ? rootProject.ext.androidxFragmentVersion : '1.9.1'
7
+ androidxWebkitVersion = rootProject.hasProperty('androidxWebkitVersion') ? rootProject.ext.androidxWebkitVersion : '1.17.1'
8
+ junitVersion = rootProject.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
9
+ androidxJunitVersion = rootProject.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0'
10
+ androidxEspressoCoreVersion = rootProject.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0'
11
11
  }
12
12
 
13
13
 
@@ -40,9 +40,9 @@ if (System.getenv("CAP_PUBLISH") == "true") {
40
40
 
41
41
  android {
42
42
  namespace = "com.getcapacitor.android"
43
- compileSdk = project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 37
43
+ compileSdk = rootProject.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 37
44
44
  defaultConfig {
45
- minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 26
45
+ minSdkVersion rootProject.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 26
46
46
  versionCode 1
47
47
  versionName "1.0"
48
48
  consumerProguardFiles 'proguard-rules.pro'
@@ -882,11 +882,24 @@ var nativeBridge = (function (exports) {
882
882
  try {
883
883
  if (typeof postToNative === 'function') {
884
884
  let callbackId = '-1';
885
- if (storedCallback &&
885
+ // native never answers removeListener nor sends `save: false` for a removed listener,
886
+ // so release those callbacks here, otherwise everything they capture is never freed
887
+ if (methodName === 'removeListener') {
888
+ callbacks.delete(options === null || options === void 0 ? void 0 : options.callbackId);
889
+ }
890
+ else if (methodName === 'removeAllListeners') {
891
+ callbacks.forEach((stored, id) => {
892
+ if (stored.pluginName === pluginName && stored.methodName === 'addListener') {
893
+ callbacks.delete(id);
894
+ }
895
+ });
896
+ }
897
+ if (methodName !== 'removeListener' &&
898
+ storedCallback &&
886
899
  (typeof storedCallback.callback === 'function' || typeof storedCallback.resolve === 'function')) {
887
900
  // store the call for later lookup
888
901
  callbackId = String(++callbackIdCount);
889
- callbacks.set(callbackId, storedCallback);
902
+ callbacks.set(callbackId, Object.assign(Object.assign({}, storedCallback), { pluginName, methodName }));
890
903
  }
891
904
  const callData = {
892
905
  callbackId: callbackId,
@@ -7,16 +7,20 @@ package com.getcapacitor;
7
7
  import android.content.Context;
8
8
  import android.content.res.AssetManager;
9
9
  import android.net.Uri;
10
+ import android.os.Environment;
10
11
  import android.util.TypedValue;
11
12
  import java.io.File;
12
13
  import java.io.FileInputStream;
14
+ import java.io.FileNotFoundException;
13
15
  import java.io.IOException;
14
16
  import java.io.InputStream;
17
+ import java.util.ArrayList;
15
18
  import java.util.List;
16
19
 
17
20
  public class AndroidProtocolHandler {
18
21
 
19
22
  private Context context;
23
+ private List<File> appStorageRoots;
20
24
 
21
25
  public AndroidProtocolHandler(Context context) {
22
26
  this.context = context;
@@ -57,7 +61,8 @@ public class AndroidProtocolHandler {
57
61
  }
58
62
 
59
63
  private static int getFieldId(Context context, String assetType, String assetName)
60
- throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
64
+ throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException
65
+ {
61
66
  Class<?> d = context.getClassLoader().loadClass(context.getPackageName() + ".R$" + assetType);
62
67
  java.lang.reflect.Field field = d.getField(assetName);
63
68
  return field.getInt(null);
@@ -69,6 +74,125 @@ public class AndroidProtocolHandler {
69
74
  return new FileInputStream(localFile);
70
75
  }
71
76
 
77
+ /**
78
+ * Opens a file served from the base path the app is hosted from (see {@code setServerBasePath}).
79
+ * The request path is decoded by {@link Uri#getPath()}, so an encoded slash ({@code %2F}) can carry
80
+ * {@code ..} segments that the browser did not resolve. The resolved file must therefore sit inside
81
+ * the base path, or the request would read any file the app can read.
82
+ *
83
+ * @param basePath the directory the app is hosted from
84
+ * @param filePath the base path followed by the request path
85
+ * @throws FileNotFoundException if the resolved file is outside of the base path
86
+ */
87
+ public InputStream openBasePathFile(String basePath, String filePath) throws IOException {
88
+ String base = new File(basePath).getCanonicalPath();
89
+ File file = new File(filePath).getCanonicalFile();
90
+ String resolved = file.getPath();
91
+ if (!resolved.equals(base) && !resolved.startsWith(base.endsWith(File.separator) ? base : base + File.separator)) {
92
+ throw new FileNotFoundException("File is outside of the base path: " + filePath);
93
+ }
94
+ return new FileInputStream(file);
95
+ }
96
+
97
+ /**
98
+ * Opens a file whose location was chosen by a {@link RouteProcessor}. The processor may map requests
99
+ * outside the base path on purpose, so containment is not checked here. The request path is decoded
100
+ * by {@link Uri#getPath()}, so an encoded slash ({@code %2F}) can still carry {@code ..} segments that
101
+ * the browser did not resolve and that a processor would pass on; such requests are refused.
102
+ *
103
+ * @param requestPath the decoded request path
104
+ * @param processedPath the file path returned by the route processor
105
+ * @throws FileNotFoundException if the request path contains a parent-directory segment
106
+ */
107
+ public InputStream openRoutedFile(String requestPath, String processedPath) throws IOException {
108
+ for (String segment : requestPath.split("/")) {
109
+ if (segment.equals("..")) {
110
+ throw new FileNotFoundException("Parent-directory segment in request path: " + requestPath);
111
+ }
112
+ }
113
+ return openFile(processedPath);
114
+ }
115
+
116
+ /**
117
+ * Opens a file requested through the {@link Bridge#CAPACITOR_FILE_START} proxy route.
118
+ * Unlike {@link #openFile(String)}, the resolved path must sit inside the app's own storage or
119
+ * shared/external storage, so the route cannot expose app-private data (shared_prefs, databases)
120
+ * or system files such as /proc or /etc.
121
+ *
122
+ * @param filePath the request path, starting with {@link Bridge#CAPACITOR_FILE_START}
123
+ * @throws IOException if the file cannot be opened or its location is not allowed
124
+ */
125
+ public InputStream openProxiedFile(String filePath) throws IOException {
126
+ String realPath = filePath.startsWith(Bridge.CAPACITOR_FILE_START)
127
+ ? filePath.substring(Bridge.CAPACITOR_FILE_START.length())
128
+ : filePath;
129
+ // Canonicalizing resolves ".." segments and symlinks; open the resolved file so the checked path is the read one.
130
+ File canonicalFile = new File(realPath).getCanonicalFile();
131
+ if (!isInAllowedLocation(canonicalFile)) {
132
+ throw new IOException("Path is outside the locations served by the file proxy: " + realPath);
133
+ }
134
+ return new FileInputStream(canonicalFile);
135
+ }
136
+
137
+ private boolean isInAllowedLocation(File canonicalFile) throws IOException {
138
+ String path = canonicalFile.getPath();
139
+ for (File root : getAllowedRoots()) {
140
+ String rootPath = root.getCanonicalPath();
141
+ if (path.equals(rootPath) || path.startsWith(rootPath + File.separator)) {
142
+ return true;
143
+ }
144
+ }
145
+ return false;
146
+ }
147
+
148
+ @SuppressWarnings("deprecation")
149
+ /**
150
+ * The app's files and cache directories (Filesystem Data/Library/Cache, Camera temporary images). They do not
151
+ * change while the app runs, unlike the external storage roots, so they are looked up once.
152
+ */
153
+ private List<File> getAppStorageRoots() {
154
+ List<File> roots = appStorageRoots;
155
+ if (roots == null) {
156
+ roots = new ArrayList<>();
157
+ addIfNotNull(roots, context.getFilesDir());
158
+ addIfNotNull(roots, context.getCacheDir());
159
+ appStorageRoots = roots;
160
+ }
161
+ return roots;
162
+ }
163
+
164
+ private List<File> getAllowedRoots() {
165
+ List<File> roots = new ArrayList<>(getAppStorageRoots());
166
+ // Primary shared storage (Filesystem Documents/ExternalStorage, gallery and media picks)
167
+ addIfNotNull(roots, Environment.getExternalStorageDirectory());
168
+ // App-specific external dirs, and the root of every other volume (e.g. SD cards) they live on
169
+ List<File> externalDirs = new ArrayList<>();
170
+ for (File dir : context.getExternalFilesDirs(null)) {
171
+ externalDirs.add(dir);
172
+ }
173
+ for (File dir : context.getExternalCacheDirs()) {
174
+ externalDirs.add(dir);
175
+ }
176
+ for (File dir : externalDirs) {
177
+ if (dir == null) {
178
+ continue;
179
+ }
180
+ roots.add(dir);
181
+ String dirPath = dir.getPath();
182
+ int androidDirIndex = dirPath.indexOf("/Android/");
183
+ if (androidDirIndex > 0) {
184
+ roots.add(new File(dirPath.substring(0, androidDirIndex)));
185
+ }
186
+ }
187
+ return roots;
188
+ }
189
+
190
+ private static void addIfNotNull(List<File> roots, File dir) {
191
+ if (dir != null) {
192
+ roots.add(dir);
193
+ }
194
+ }
195
+
72
196
  public InputStream openContentUrl(Uri uri) throws IOException {
73
197
  Integer port = uri.getPort();
74
198
  String baseUrl = uri.getScheme() + "://" + uri.getHost();
@@ -80,7 +204,10 @@ public class AndroidProtocolHandler {
80
204
  InputStream stream = null;
81
205
  try {
82
206
  stream = context.getContentResolver().openInputStream(Uri.parse(realPath));
83
- } catch (SecurityException e) {
207
+ } catch (RuntimeException e) {
208
+ // The target provider runs in this process and may throw unchecked exceptions for a malformed or
209
+ // unknown path (e.g. FileProvider throws IllegalArgumentException, older versions
210
+ // StringIndexOutOfBoundsException). Left uncaught they crash the app, so report "not found" instead.
84
211
  Logger.error("Unable to open content URL: " + uri, e);
85
212
  }
86
213
  return stream;
@@ -302,10 +302,23 @@ public class Bridge {
302
302
  }
303
303
  }
304
304
 
305
+ /**
306
+ * Whether the path targets the local file or content proxy routes.
307
+ */
308
+ static boolean isLocalFilePath(String path) {
309
+ return path != null && (path.startsWith(CAPACITOR_FILE_START) || path.startsWith(CAPACITOR_CONTENT_START));
310
+ }
311
+
312
+ /**
313
+ * Whether the path targets one of the internal proxy routes (file, content, http interceptor).
314
+ */
315
+ static boolean isInternalProxyPath(String path) {
316
+ return isLocalFilePath(path) || (path != null && path.startsWith(CAPACITOR_HTTP_INTERCEPTOR_START));
317
+ }
318
+
305
319
  public boolean launchIntent(Uri url) {
306
- // The proxy returns a remote body at the app origin, so block it before plugins can allow it.
307
- String path = url.getPath();
308
- if (path != null && path.startsWith(CAPACITOR_HTTP_INTERCEPTOR_START)) {
320
+ // The proxy routes return data at the app origin, so block navigating to them before plugins can allow it.
321
+ if (isInternalProxyPath(url.getPath())) {
309
322
  return true;
310
323
  }
311
324
 
@@ -103,7 +103,8 @@ public class PluginHandle {
103
103
  * @throws InvalidPluginMethodException if no method was found on that plugin
104
104
  */
105
105
  public void invoke(String methodName, PluginCall call)
106
- throws PluginLoadException, InvalidPluginMethodException, InvocationTargetException, IllegalAccessException {
106
+ throws PluginLoadException, InvalidPluginMethodException, InvocationTargetException, IllegalAccessException
107
+ {
107
108
  if (this.instance == null) {
108
109
  // Can throw PluginLoadException
109
110
  this.load();
@@ -25,6 +25,7 @@ import android.webkit.WebResourceRequest;
25
25
  import android.webkit.WebResourceResponse;
26
26
  import com.getcapacitor.plugin.util.CapacitorHttpUrlConnection;
27
27
  import com.getcapacitor.plugin.util.HttpRequestHandler;
28
+ import java.io.ByteArrayInputStream;
28
29
  import java.io.IOException;
29
30
  import java.io.InputStream;
30
31
  import java.net.HttpURLConnection;
@@ -171,10 +172,15 @@ public class WebViewLocalServer {
171
172
  public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
172
173
  Uri loadingUrl = request.getUrl();
173
174
 
175
+ if (Bridge.isInternalProxyPath(loadingUrl.getPath()) && !isProxyRequestAllowed(request)) {
176
+ // Internal proxy routes are only for sub-resources requested at the app's own origin.
177
+ Logger.warn("Blocked request to internal proxy route: " + loadingUrl);
178
+ return buildBlockedResponse();
179
+ }
180
+
174
181
  if (null != loadingUrl.getPath() && loadingUrl.getPath().startsWith(Bridge.CAPACITOR_HTTP_INTERCEPTOR_START)) {
175
- // Only fetch/XHR should reach the proxy; a document would run remote content at the app origin.
176
182
  boolean httpEnabled = bridge.getConfig().getPluginConfiguration("CapacitorHttp").getBoolean("enabled", false);
177
- if (!httpEnabled || isDocumentRequest(request)) {
183
+ if (!httpEnabled) {
178
184
  return null;
179
185
  }
180
186
  Logger.debug("Handling CapacitorHttp request: " + loadingUrl);
@@ -202,6 +208,47 @@ public class WebViewLocalServer {
202
208
  }
203
209
  }
204
210
 
211
+ /**
212
+ * Internal proxy routes (file, content, http interceptor) return data at the app origin, so they must only
213
+ * serve sub-resource requests (img, media, fetch/XHR) made to the app's own origin. A document would run
214
+ * the returned content with the app's privileges, and a request to any other origin has no business here.
215
+ */
216
+ private boolean isProxyRequestAllowed(WebResourceRequest request) {
217
+ return isAppOrigin(request.getUrl()) && !isDocumentRequest(request);
218
+ }
219
+
220
+ private boolean isAppOrigin(Uri uri) {
221
+ String localUrl = bridge.getLocalUrl();
222
+ if (localUrl == null || uri.getScheme() == null || uri.getHost() == null) {
223
+ return false;
224
+ }
225
+ Uri appOrigin = Uri.parse(localUrl);
226
+ return (
227
+ uri.getScheme().equalsIgnoreCase(appOrigin.getScheme()) &&
228
+ uri.getHost().equalsIgnoreCase(appOrigin.getHost()) &&
229
+ getEffectivePort(uri) == getEffectivePort(appOrigin)
230
+ );
231
+ }
232
+
233
+ /**
234
+ * The WebView hands over request URLs without a default port, while the configured app URL may spell it out
235
+ * (e.g. server.url "http://host:80"), so a missing port is treated as the scheme's default.
236
+ */
237
+ private static int getEffectivePort(Uri uri) {
238
+ int port = uri.getPort();
239
+ if (port != -1) {
240
+ return port;
241
+ }
242
+ String scheme = uri.getScheme();
243
+ if ("https".equalsIgnoreCase(scheme)) {
244
+ return 443;
245
+ }
246
+ if ("http".equalsIgnoreCase(scheme)) {
247
+ return 80;
248
+ }
249
+ return -1;
250
+ }
251
+
205
252
  /** isForMainFrame() is false for an iframe and a fetch alike; only navigations send this header. */
206
253
  private boolean isDocumentRequest(WebResourceRequest request) {
207
254
  if (request.isForMainFrame()) {
@@ -221,8 +268,7 @@ public class WebViewLocalServer {
221
268
  }
222
269
 
223
270
  private boolean isLocalFile(Uri uri) {
224
- String path = uri.getPath();
225
- return path.startsWith(capacitorContentStart) || path.startsWith(capacitorFileStart);
271
+ return Bridge.isLocalFilePath(uri.getPath());
226
272
  }
227
273
 
228
274
  private boolean isErrorUrl(Uri uri) {
@@ -326,7 +372,9 @@ public class WebViewLocalServer {
326
372
  encoding = encodingParts[1].trim();
327
373
  }
328
374
  }
329
- } else {
375
+ } else if (!"Access-Control-Allow-Origin".equalsIgnoreCase(entry.getKey())) {
376
+ // The target's CORS grant is not forwarded: the request is made natively (with the app's cookies), so a
377
+ // grant meant for the target's own callers would let another origin read the response.
330
378
  responseHeaders.put(entry.getKey(), builder.toString());
331
379
  }
332
380
  }
@@ -349,6 +397,27 @@ public class WebViewLocalServer {
349
397
  return new WebResourceResponse(mimeType, encoding, responseCode, reasonPhrase, responseHeaders, inputStream);
350
398
  }
351
399
 
400
+ /**
401
+ * A fixed rejection for a blocked proxy route request. Returning null would let the WebView send the request
402
+ * to the network itself, which for a remote server.url puts the local path in a request to that server.
403
+ */
404
+ private WebResourceResponse buildBlockedResponse() {
405
+ Map<String, String> headers = new HashMap<>();
406
+ headers.put("Content-Security-Policy", "sandbox; frame-ancestors 'none'");
407
+ headers.put("Cache-Control", "no-store");
408
+ return new WebResourceResponse("text/plain", "UTF-8", 403, "Forbidden", headers, new ByteArrayInputStream(new byte[0]));
409
+ }
410
+
411
+ /**
412
+ * Files served through the file/content proxy routes are data, not pages. If anything ends up rendering one,
413
+ * the sandbox keeps it inert and off the app origin, and it cannot be framed.
414
+ */
415
+ void addProxyRouteSecurityHeaders(Uri uri, Map<String, String> responseHeaders) {
416
+ if (isLocalFile(uri)) {
417
+ responseHeaders.put("Content-Security-Policy", "sandbox; frame-ancestors 'none'");
418
+ }
419
+ }
420
+
352
421
  private WebResourceResponse handleLocalRequest(WebResourceRequest request, PathHandler handler) {
353
422
  String path = request.getUrl().getPath();
354
423
 
@@ -362,15 +431,22 @@ public class WebViewLocalServer {
362
431
  int statusCode = 206;
363
432
  try {
364
433
  int totalRange = responseStream.available();
365
- String[] parts = rangeString.split("=");
366
- String[] streamParts = parts[1].split("-");
367
- String fromRange = streamParts[0];
368
- int range = totalRange - 1;
369
- if (streamParts.length > 1) {
370
- range = Integer.parseInt(streamParts[1]);
434
+ if (totalRange == -1) {
435
+ // No stream (missing or refused file): not a partial response.
436
+ statusCode = 404;
437
+ addProxyRouteSecurityHeaders(request.getUrl(), tempResponseHeaders);
438
+ } else {
439
+ String[] parts = rangeString.split("=");
440
+ String[] streamParts = parts[1].split("-");
441
+ String fromRange = streamParts[0];
442
+ int range = totalRange - 1;
443
+ if (streamParts.length > 1) {
444
+ range = Integer.parseInt(streamParts[1]);
445
+ }
446
+ tempResponseHeaders.put("Accept-Ranges", "bytes");
447
+ tempResponseHeaders.put("Content-Range", "bytes " + fromRange + "-" + range + "/" + totalRange);
448
+ addProxyRouteSecurityHeaders(request.getUrl(), tempResponseHeaders);
371
449
  }
372
- tempResponseHeaders.put("Accept-Ranges", "bytes");
373
- tempResponseHeaders.put("Content-Range", "bytes " + fromRange + "-" + range + "/" + totalRange);
374
450
  } catch (IOException e) {
375
451
  statusCode = 404;
376
452
  }
@@ -388,12 +464,14 @@ public class WebViewLocalServer {
388
464
  InputStream responseStream = new LollipopLazyInputStream(handler, request);
389
465
  String mimeType = getMimeType(request.getUrl().getPath(), responseStream);
390
466
  int statusCode = getStatusCode(responseStream, handler.getStatusCode());
467
+ Map<String, String> localResponseHeaders = handler.buildDefaultResponseHeaders();
468
+ addProxyRouteSecurityHeaders(request.getUrl(), localResponseHeaders);
391
469
  return new WebResourceResponse(
392
470
  mimeType,
393
471
  handler.getEncoding(),
394
472
  statusCode,
395
473
  handler.getReasonPhrase(),
396
- handler.buildDefaultResponseHeaders(),
474
+ localResponseHeaders,
397
475
  responseStream
398
476
  );
399
477
  }
@@ -667,13 +745,14 @@ public class WebViewLocalServer {
667
745
  if (path.startsWith(capacitorContentStart)) {
668
746
  stream = protocolHandler.openContentUrl(url);
669
747
  } else if (path.startsWith(capacitorFileStart)) {
670
- stream = protocolHandler.openFile(path);
748
+ stream = protocolHandler.openProxiedFile(path);
671
749
  } else if (!isAsset) {
672
750
  if (routeProcessor == null) {
673
- path = basePath + url.getPath();
751
+ // The decoded path can contain ".." that must not leave the base path.
752
+ stream = protocolHandler.openBasePathFile(basePath, basePath + url.getPath());
753
+ } else {
754
+ stream = protocolHandler.openRoutedFile(url.getPath(), path);
674
755
  }
675
-
676
- stream = protocolHandler.openFile(path);
677
756
  } else if (ignoreAssetPath) {
678
757
  stream = protocolHandler.openAsset(path);
679
758
  } else {
@@ -7,6 +7,7 @@ import android.content.res.Resources;
7
7
  import android.util.TypedValue;
8
8
  import android.view.View;
9
9
  import android.view.Window;
10
+ import android.view.WindowManager;
10
11
  import android.webkit.WebView;
11
12
  import androidx.core.graphics.Insets;
12
13
  import androidx.core.view.ViewCompat;
@@ -21,6 +22,8 @@ import com.getcapacitor.PluginMethod;
21
22
  import com.getcapacitor.WebViewListener;
22
23
  import com.getcapacitor.annotation.CapacitorPlugin;
23
24
  import java.util.Locale;
25
+ import java.util.regex.Matcher;
26
+ import java.util.regex.Pattern;
24
27
 
25
28
  @CapacitorPlugin
26
29
  public class SystemBars extends Plugin {
@@ -37,8 +40,7 @@ public class SystemBars extends Plugin {
37
40
 
38
41
  // https://issues.chromium.org/issues/40699457
39
42
  private static final int WEBVIEW_VERSION_WITH_SAFE_AREA_FIX = 140;
40
- // https://issues.chromium.org/issues/457682720
41
- private static final int WEBVIEW_VERSION_WITH_SAFE_AREA_KEYBOARD_FIX = 144;
43
+ private static final Pattern WEBVIEW_MAJOR_VERSION_PATTERN = Pattern.compile("\\d+");
42
44
 
43
45
  static final String viewportMetaJSFunction = """
44
46
  function capacitorSystemBarsCheckMetaViewport() {
@@ -195,23 +197,28 @@ public class SystemBars extends Plugin {
195
197
 
196
198
  Insets systemBarsInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout());
197
199
  Insets imeInsets = insets.getInsets(WindowInsetsCompat.Type.ime());
198
- boolean keyboardVisible = insets.isVisible(WindowInsetsCompat.Type.ime());
200
+ // With `adjustNothing` the keyboard overlays the WebView, so it is handled as if it is not there
201
+ boolean keyboardOverlaysWebView =
202
+ (getActivity().getWindow().getAttributes().softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) ==
203
+ WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
204
+ boolean keyboardVisible = !keyboardOverlaysWebView && insets.isVisible(WindowInsetsCompat.Type.ime());
199
205
 
200
206
  if (shouldPassthroughInsets) {
201
207
  // We need to correct for a possible shown IME
202
208
  v.setPadding(0, 0, 0, keyboardVisible ? imeInsets.bottom : 0);
203
209
 
204
- WindowInsetsCompat newInsets = new WindowInsetsCompat.Builder(insets)
205
- .setInsets(
210
+ WindowInsetsCompat newInsets = withoutOverlayingKeyboard(
211
+ new WindowInsetsCompat.Builder(insets).setInsets(
206
212
  WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout(),
207
213
  Insets.of(
208
214
  systemBarsInsets.left,
209
215
  systemBarsInsets.top,
210
216
  systemBarsInsets.right,
211
- getBottomInset(systemBarsInsets, keyboardVisible)
217
+ getBottomInset(systemBarsInsets, imeInsets, keyboardVisible)
212
218
  )
213
- )
214
- .build();
219
+ ),
220
+ keyboardOverlaysWebView
221
+ ).build();
215
222
 
216
223
  injectSafeAreaCSS(newInsets);
217
224
 
@@ -229,9 +236,13 @@ public class SystemBars extends Plugin {
229
236
  // Returning `WindowInsetsCompat.CONSUMED` breaks recalculation of safe area insets
230
237
  // So we have to explicitly set insets to `0`
231
238
  // See: https://issues.chromium.org/issues/461332423
232
- WindowInsetsCompat newInsets = new WindowInsetsCompat.Builder(insets)
233
- .setInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout(), Insets.of(0, 0, 0, 0))
234
- .build();
239
+ WindowInsetsCompat newInsets = withoutOverlayingKeyboard(
240
+ new WindowInsetsCompat.Builder(insets).setInsets(
241
+ WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout(),
242
+ Insets.of(0, 0, 0, 0)
243
+ ),
244
+ keyboardOverlaysWebView
245
+ ).build();
235
246
 
236
247
  injectSafeAreaCSS(newInsets);
237
248
 
@@ -239,21 +250,31 @@ public class SystemBars extends Plugin {
239
250
  });
240
251
  }
241
252
 
253
+ private WindowInsetsCompat.Builder withoutOverlayingKeyboard(WindowInsetsCompat.Builder builder, boolean keyboardOverlaysWebView) {
254
+ if (!keyboardOverlaysWebView) {
255
+ return builder;
256
+ }
257
+
258
+ // WebView >= 139 shrinks its visual viewport for the IME insets it receives, which makes the page pannable above the keyboard.
259
+ // Unlike Chrome it ignores `VirtualKeyboard.overlaysContent` and `interactive-widget=overlays-content`,
260
+ // so not handing it the IME insets is the only way to opt out.
261
+ // Setting them to `0` rather than consuming them keeps the WebView's inset state up to date.
262
+ // See: https://developer.android.com/develop/ui/views/layout/webapps/understand-window-insets
263
+ return builder.setInsets(WindowInsetsCompat.Type.ime(), Insets.NONE).setVisible(WindowInsetsCompat.Type.ime(), false);
264
+ }
265
+
242
266
  private void injectSafeAreaCSS(WindowInsetsCompat insets) {
243
267
  if (!INSETS_HANDLING_CSS.equals(insetsHandling)) {
244
268
  return;
245
269
  }
246
270
 
247
271
  Insets systemBarsInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout());
248
- boolean keyboardVisible = insets.isVisible(WindowInsetsCompat.Type.ime());
249
272
 
250
273
  // Convert pixels to density-independent pixels
251
274
  float density = getActivity().getResources().getDisplayMetrics().density;
252
275
  float topPx = systemBarsInsets.top / density;
253
276
  float rightPx = systemBarsInsets.right / density;
254
- // For native insets the value gets automatically corrected when the IME is visible (in newer WebView versions),
255
- // but for these injected values we have to handle that manually (for all WebView versions).
256
- float bottomPx = (keyboardVisible ? 0 : systemBarsInsets.bottom) / density;
277
+ float bottomPx = systemBarsInsets.bottom / density;
257
278
  float leftPx = systemBarsInsets.left / density;
258
279
 
259
280
  // Execute JavaScript to inject the CSS
@@ -342,23 +363,33 @@ public class SystemBars extends Plugin {
342
363
 
343
364
  private Integer getWebViewMajorVersion() {
344
365
  PackageInfo info = WebViewCompat.getCurrentWebViewPackage(getContext());
345
- if (info != null && info.versionName != null) {
346
- String[] versionSegments = info.versionName.split("\\.");
347
- return Integer.valueOf(versionSegments[0]);
366
+ return info != null ? parseWebViewMajorVersion(info.versionName) : 0;
367
+ }
368
+
369
+ static int parseWebViewMajorVersion(String versionName) {
370
+ if (versionName == null) {
371
+ return 0;
348
372
  }
349
373
 
350
- return 0;
351
- }
374
+ Matcher matcher = WEBVIEW_MAJOR_VERSION_PATTERN.matcher(versionName);
375
+ if (!matcher.find()) {
376
+ return 0;
377
+ }
352
378
 
353
- private int getBottomInset(Insets systemBarsInsets, boolean keyboardVisible) {
354
- if (getWebViewMajorVersion() < WEBVIEW_VERSION_WITH_SAFE_AREA_KEYBOARD_FIX) {
355
- // This is a workaround for webview versions that have a bug
356
- // that causes the bottom inset to be incorrect if the IME is visible
357
- // See: https://issues.chromium.org/issues/457682720
379
+ try {
380
+ return Integer.parseInt(matcher.group());
381
+ } catch (NumberFormatException e) {
382
+ return 0;
383
+ }
384
+ }
358
385
 
359
- if (keyboardVisible) {
360
- return 0;
361
- }
386
+ private int getBottomInset(Insets systemBarsInsets, Insets imeInsets, boolean keyboardVisible) {
387
+ // Only the part of the navigation bar the IME doesn't cover is left for the page to clear:
388
+ // none for a docked IME, all of it for a floating one.
389
+ // Deliberately not gated on the WebView version: measured on 148-156, Chromium corrects
390
+ // this itself on API 35+ but not on API 29-34.
391
+ if (keyboardVisible) {
392
+ return Math.max(0, systemBarsInsets.bottom - imeInsets.bottom);
362
393
  }
363
394
 
364
395
  return systemBarsInsets.bottom;
@@ -122,7 +122,8 @@ public class HttpRequestHandler {
122
122
  }
123
123
 
124
124
  public HttpURLConnectionBuilder setUrlParams(JSObject params, boolean shouldEncode)
125
- throws URISyntaxException, MalformedURLException {
125
+ throws URISyntaxException, MalformedURLException
126
+ {
126
127
  String initialQuery = url.getQuery();
127
128
  String initialQueryBuilderStr = initialQuery == null ? "" : initialQuery;
128
129
 
@@ -212,7 +213,8 @@ public class HttpRequestHandler {
212
213
  * @throws JSONException Thrown if the JSON is unable to be parsed
213
214
  */
214
215
  public static JSObject buildResponse(CapacitorHttpUrlConnection connection, ResponseType responseType)
215
- throws IOException, JSONException {
216
+ throws IOException, JSONException
217
+ {
216
218
  int statusCode = connection.getResponseCode();
217
219
 
218
220
  JSObject output = new JSObject();
@@ -383,7 +385,8 @@ public class HttpRequestHandler {
383
385
  * @throws JSONException thrown when the incoming JSON is malformed
384
386
  */
385
387
  public static JSObject request(PluginCall call, String httpMethod, Bridge bridge)
386
- throws IOException, URISyntaxException, JSONException {
388
+ throws IOException, URISyntaxException, JSONException
389
+ {
387
390
  String urlString = call.getString("url", "");
388
391
  JSObject headers = call.getObject("headers", new JSObject());
389
392
  JSObject params = call.getObject("params", new JSObject());
@@ -10,8 +10,11 @@ public class InternalUtils {
10
10
  return InternalUtils.getPackageInfo(pm, packageName, 0);
11
11
  }
12
12
 
13
- public static PackageInfo getPackageInfo(PackageManager pm, String packageName, long flags)
14
- throws PackageManager.NameNotFoundException {
13
+ public static PackageInfo getPackageInfo(
14
+ PackageManager pm,
15
+ String packageName,
16
+ long flags
17
+ ) throws PackageManager.NameNotFoundException {
15
18
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
16
19
  return pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags));
17
20
  } else {
@@ -20,8 +23,11 @@ public class InternalUtils {
20
23
  }
21
24
 
22
25
  @SuppressWarnings("deprecation")
23
- private static PackageInfo getPackageInfoLegacy(PackageManager pm, String packageName, long flags)
24
- throws PackageManager.NameNotFoundException {
26
+ private static PackageInfo getPackageInfoLegacy(
27
+ PackageManager pm,
28
+ String packageName,
29
+ long flags
30
+ ) throws PackageManager.NameNotFoundException {
25
31
  return pm.getPackageInfo(packageName, (int) flags);
26
32
  }
27
33
  }
@@ -0,0 +1,3 @@
1
+ #This is the verification token for the com.capacitorjs:core SDK.
2
+ #Wed Nov 25 06:17:42 PST 2026
3
+ token=NZJN2KULTRABDMHADZWX32DZIE
@@ -1,6 +1,6 @@
1
1
  ext {
2
- androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.8.0'
3
- cordovaAndroidVersion = project.hasProperty('cordovaAndroidVersion') ? rootProject.ext.cordovaAndroidVersion : '15.1.0'
2
+ androidxAppCompatVersion = rootProject.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.8.0'
3
+ cordovaAndroidVersion = rootProject.hasProperty('cordovaAndroidVersion') ? rootProject.ext.cordovaAndroidVersion : '15.1.0'
4
4
  }
5
5
 
6
6
  buildscript {
@@ -17,9 +17,9 @@ apply plugin: 'com.android.library'
17
17
 
18
18
  android {
19
19
  namespace = "com.getcapacitor.cordova"
20
- compileSdk = project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 37
20
+ compileSdk = rootProject.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 37
21
21
  defaultConfig {
22
- minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 26
22
+ minSdkVersion rootProject.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 26
23
23
  versionCode 1
24
24
  versionName "1.0"
25
25
  consumerProguardFiles 'proguard-rules.pro'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capacitor/android",
3
- "version": "9.0.0-rc.0",
3
+ "version": "9.0.0",
4
4
  "description": "Capacitor: Cross-platform apps with JavaScript and the web",
5
5
  "homepage": "https://capacitorjs.com",
6
6
  "author": "Ionic Team <hi@ionic.io> (https://ionic.io)",
@@ -26,7 +26,7 @@
26
26
  "verify": "./gradlew :capacitor-android:clean :capacitor-android:lint :capacitor-android:build :capacitor-android:test"
27
27
  },
28
28
  "peerDependencies": {
29
- "@capacitor/core": "^9.0.0-rc.0"
29
+ "@capacitor/core": "^9.0.0"
30
30
  },
31
31
  "publishConfig": {
32
32
  "access": "public"