Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -336,11 +336,11 @@ Transport differs per platform but the payload does not:
| --- | --- | --- |
| Web → native | `window.webkit.messageHandlers.bridge.postMessage(obj)` — a real object; `type` defaulted to `'message'` | `window.androidBridge.postMessage(JSON.stringify(obj))` — a string |
| Native → web | `webView.evaluateJavaScript("window.Capacitor.fromNative({…})")` | `JavaScriptReplyProxy.postMessage(json)` → `androidBridge.onmessage` → `returnResult(JSON.parse(e.data))`; legacy fallback is `evaluateJavascript("window.Capacitor.fromNative(…)")` |
| Sync web → native | `prompt(JSON.stringify({ type: … }))` intercepted in `runJavaScriptTextInputPanelWithPrompt` | dedicated `@JavascriptInterface` objects (`CapacitorCookiesAndroidInterface`, `CapacitorHttpAndroidInterface`) |
| Sync web → native | `prompt(JSON.stringify({ type: … }))` intercepted in `runJavaScriptTextInputPanelWithPrompt` | dedicated `@JavascriptInterface` objects (`CapacitorCookiesAndroidInterface`, `CapacitorHttpAndroidInterface`) registered only when enabled (Android reads `window.CapacitorNativeConfig` first and uses `isEnabled()` only as a fallback) |

The synchronous `prompt()` channel on iOS serves `document.cookie` and the
"is CapacitorHttp enabled?" check, both of which must answer synchronously; `WKWebView`
offers no synchronous message handler.
The synchronous `prompt()` channel on iOS serves `document.cookie`, which must answer
synchronously; `WKWebView` offers no synchronous message handler. Whether CapacitorHttp and
CapacitorCookies are enabled is read from the injected `window.CapacitorNativeConfig`.

#### What can cross the bridge

Expand Down Expand Up @@ -590,11 +590,12 @@ is the optional interception of `fetch`, `XMLHttpRequest` and `document.cookie`.
| `plugins.CapacitorCookies.enabled` | Redefines the `document.cookie` property descriptor |

The web layer must know the switch state *before* any app script runs, which is why the
check is synchronous: on iOS via the `prompt()` channel
(`{ type: 'CapacitorHttp' }`, `{ type: 'CapacitorCookies.isEnabled' }`), on Android via
the `@JavascriptInterface` methods `CapacitorHttpAndroidInterface.isEnabled()` and
`CapacitorCookiesAndroidInterface.isEnabled()`. Both interfaces are installed by the
plugins themselves in `load()` — see `CapacitorHttp.java` and `CapacitorCookies.java`.
check is synchronous: iOS and Android read `window.CapacitorNativeConfig` first; on Android,
if `window.CapacitorNativeConfig` is absent, the bridge falls back to the
`@JavascriptInterface` methods `CapacitorHttpAndroidInterface.isEnabled()` and
`CapacitorCookiesAndroidInterface.isEnabled()`. Both Android interfaces are registered by
the plugins in `load()` only when the plugin is enabled — see `CapacitorHttp.java` and
`CapacitorCookies.java`.

Before patching, the originals are stashed on `window` as `CapacitorWebFetch` and
`CapacitorWebXMLHttpRequest`, so the patched implementations can delegate.
Expand Down
26 changes: 9 additions & 17 deletions android/capacitor/src/main/assets/native-bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ var nativeBridge = (function (exports) {
try {
data = JSON.parse(data);
}
catch (ignored) {
catch (_a) {
// ignore
}
type = 'json';
Expand Down Expand Up @@ -314,7 +314,7 @@ var nativeBridge = (function (exports) {
win.Ionic.WebView = IonicWebView;
};
const initLogger = (win, cap) => {
var _a, _b;
var _a, _b, _c, _d;
const BRIDGED_CONSOLE_METHODS = ['debug', 'error', 'info', 'log', 'trace', 'warn'];
const createLogFromNative = (c) => (result) => {
if (isFullConsole(c)) {
Expand Down Expand Up @@ -363,7 +363,7 @@ var nativeBridge = (function (exports) {
}
return String(msg);
}
catch (e) {
catch (_a) {
return '';
}
};
Expand All @@ -381,10 +381,8 @@ var nativeBridge = (function (exports) {
}
}
else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') {
const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled();
if (isCookiesEnabled === true) {
doPatchCookies = true;
}
doPatchCookies =
((_c = (_b = win.CapacitorNativeConfig) === null || _b === void 0 ? void 0 : _b.cookiesEnabled) !== null && _c !== void 0 ? _c : win.CapacitorCookiesAndroidInterface.isEnabled()) === true;
}
if (doPatchCookies) {
Object.defineProperty(document, 'cookie', {
Expand Down Expand Up @@ -442,16 +440,11 @@ var nativeBridge = (function (exports) {
};
let doPatchHttp = false;
// check if capacitor http is disabled before patching
if (platform === 'ios') {
if (((_b = win.CapacitorNativeConfig) === null || _b === void 0 ? void 0 : _b.httpEnabled) === true) {
doPatchHttp = true;
}
if (((_d = win.CapacitorNativeConfig) === null || _d === void 0 ? void 0 : _d.httpEnabled) != null) {
doPatchHttp = win.CapacitorNativeConfig.httpEnabled === true;
}
else if (typeof win.CapacitorHttpAndroidInterface !== 'undefined') {
const isHttpEnabled = win.CapacitorHttpAndroidInterface.isEnabled();
if (isHttpEnabled === true) {
doPatchHttp = true;
}
else if (platform === 'android' && typeof win.CapacitorHttpAndroidInterface !== 'undefined') {
doPatchHttp = win.CapacitorHttpAndroidInterface.isEnabled() === true;
}
if (doPatchHttp) {
// fetch patch
Expand Down Expand Up @@ -1006,7 +999,6 @@ var nativeBridge = (function (exports) {
});
});
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
cap.withPlugin = (_pluginId, _fn) => dummy;
cap.Exception = CapacitorException;
initEvents(win, cap);
Expand Down
4 changes: 3 additions & 1 deletion android/capacitor/src/main/java/com/getcapacitor/Bridge.java
Original file line number Diff line number Diff line change
Expand Up @@ -935,7 +935,9 @@ public <I, O> ActivityResultLauncher<I> registerForActivityResult(
*/
private JSInjector getJSInjector() {
try {
String globalJS = JSExport.getGlobalJS(context, config.isLoggingEnabled(), isDevMode());
boolean cookiesEnabled = config.getPluginConfiguration("CapacitorCookies").getBoolean("enabled", false);
boolean httpEnabled = config.getPluginConfiguration("CapacitorHttp").getBoolean("enabled", false);
String globalJS = JSExport.getGlobalJS(context, config.isLoggingEnabled(), isDevMode(), cookiesEnabled, httpEnabled);
String bridgeJS = JSExport.getBridgeJS(context);
String pluginJS = JSExport.getPluginJS(plugins.values());
String cordovaJS = JSExport.getCordovaJS(context);
Expand Down
11 changes: 11 additions & 0 deletions android/capacitor/src/main/java/com/getcapacitor/JSExport.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ public static String getGlobalJS(Context context, boolean loggingEnabled, boolea
return "window.Capacitor = { DEBUG: " + isDebug + ", isLoggingEnabled: " + loggingEnabled + ", Plugins: {} };";
}

static String getGlobalJS(Context context, boolean loggingEnabled, boolean isDebug, boolean cookiesEnabled, boolean httpEnabled) {
return (
getGlobalJS(context, loggingEnabled, isDebug) +
" window.CapacitorNativeConfig = { cookiesEnabled: " +
cookiesEnabled +
", httpEnabled: " +
httpEnabled +
" };"
);
}

public static String getMiscFileJS(ArrayList<String> paths, Context context) {
List<String> lines = new ArrayList<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ public class CapacitorCookies extends Plugin {

@Override
public void load() {
this.bridge.getWebView().addJavascriptInterface(this, "CapacitorCookiesAndroidInterface");
if (isEnabled()) {
this.bridge.getWebView().addJavascriptInterface(this, "CapacitorCookiesAndroidInterface");
}
this.cookieManager = new CapacitorCookieManager(null, java.net.CookiePolicy.ACCEPT_ALL, this.bridge);
this.cookieManager.removeSessionCookies();
CookieHandler.setDefault(this.cookieManager);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ public class CapacitorHttp extends Plugin {

@Override
public void load() {
this.bridge.getWebView().addJavascriptInterface(this, "CapacitorHttpAndroidInterface");
if (isEnabled()) {
this.bridge.getWebView().addJavascriptInterface(this, "CapacitorHttpAndroidInterface");
}
super.load();
}

Expand Down
26 changes: 26 additions & 0 deletions android/capacitor/src/test/java/com/getcapacitor/JSExportTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.getcapacitor;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class JSExportTest {

@Test
public void getGlobalJSIncludesCapacitorNativeConfigFlags() {
String js = JSExport.getGlobalJS(null, true, false, true, false);

assertEquals(
"window.Capacitor = { DEBUG: false, isLoggingEnabled: true, Plugins: {} }; " +
"window.CapacitorNativeConfig = { cookiesEnabled: true, httpEnabled: false };",
js
);
}

@Test
public void getGlobalJSThreeArgOverloadOmitsCapacitorNativeConfig() {
String js = JSExport.getGlobalJS(null, false, true);

assertEquals("window.Capacitor = { DEBUG: true, isLoggingEnabled: false, Plugins: {} };", js);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.getcapacitor.plugin;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.webkit.CookieManager;
import android.webkit.WebView;
import com.getcapacitor.Bridge;
import com.getcapacitor.CapConfig;
import com.getcapacitor.PluginConfig;
import java.net.CookieHandler;
import org.junit.Test;
import org.mockito.MockedStatic;

public class CapacitorCookiesTest {

@Test
public void loadSkipsJavascriptInterfaceWhenDisabled() {
verify(loadWithCookiesEnabled(false), never()).addJavascriptInterface(any(), anyString());
}

@Test
public void loadRegistersJavascriptInterfaceWhenEnabled() {
verify(loadWithCookiesEnabled(true)).addJavascriptInterface(any(CapacitorCookies.class), eq("CapacitorCookiesAndroidInterface"));
}

private WebView loadWithCookiesEnabled(boolean enabled) {
Bridge bridge = mock(Bridge.class);
WebView webView = mock(WebView.class);
CapConfig config = mock(CapConfig.class);
PluginConfig pluginConfig = mock(PluginConfig.class);
CookieManager webkitCookieManager = mock(CookieManager.class);

when(bridge.getWebView()).thenReturn(webView);
when(bridge.getConfig()).thenReturn(config);
when(config.getPluginConfiguration("CapacitorCookies")).thenReturn(pluginConfig);
when(pluginConfig.getBoolean("enabled", false)).thenReturn(enabled);

CookieHandler previous = CookieHandler.getDefault();
try (MockedStatic<CookieManager> cookieManagerMock = mockStatic(CookieManager.class)) {
cookieManagerMock.when(CookieManager::getInstance).thenReturn(webkitCookieManager);
CapacitorCookies plugin = new CapacitorCookies();
plugin.setBridge(bridge);
plugin.load();
} finally {
CookieHandler.setDefault(previous);
}

return webView;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.getcapacitor.plugin;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.webkit.WebView;
import com.getcapacitor.Bridge;
import com.getcapacitor.CapConfig;
import com.getcapacitor.PluginConfig;
import org.junit.Test;

public class CapacitorHttpTest {

@Test
public void loadSkipsJavascriptInterfaceWhenDisabled() {
verify(loadWithHttpEnabled(false), never()).addJavascriptInterface(any(), anyString());
}

@Test
public void loadRegistersJavascriptInterfaceWhenEnabled() {
verify(loadWithHttpEnabled(true)).addJavascriptInterface(any(CapacitorHttp.class), eq("CapacitorHttpAndroidInterface"));
}

private WebView loadWithHttpEnabled(boolean enabled) {
Bridge bridge = mock(Bridge.class);
WebView webView = mock(WebView.class);
CapConfig config = mock(CapConfig.class);
PluginConfig pluginConfig = mock(PluginConfig.class);

when(bridge.getWebView()).thenReturn(webView);
when(bridge.getConfig()).thenReturn(config);
when(config.getPluginConfiguration("CapacitorHttp")).thenReturn(pluginConfig);
when(pluginConfig.getBoolean("enabled", false)).thenReturn(enabled);

CapacitorHttp plugin = new CapacitorHttp();
plugin.setBridge(bridge);
plugin.load();

return webView;
}
}
19 changes: 6 additions & 13 deletions core/native-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,10 +391,8 @@ const initBridge = (w: any): void => {
doPatchCookies = true;
}
} else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') {
const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled();
if (isCookiesEnabled === true) {
doPatchCookies = true;
}
doPatchCookies =
(win.CapacitorNativeConfig?.cookiesEnabled ?? win.CapacitorCookiesAndroidInterface.isEnabled()) === true;
}

if (doPatchCookies) {
Expand Down Expand Up @@ -459,15 +457,10 @@ const initBridge = (w: any): void => {
let doPatchHttp = false;

// check if capacitor http is disabled before patching
if (platform === 'ios') {
if (win.CapacitorNativeConfig?.httpEnabled === true) {
doPatchHttp = true;
}
} else if (typeof win.CapacitorHttpAndroidInterface !== 'undefined') {
const isHttpEnabled = win.CapacitorHttpAndroidInterface.isEnabled();
if (isHttpEnabled === true) {
doPatchHttp = true;
}
if (win.CapacitorNativeConfig?.httpEnabled != null) {
doPatchHttp = win.CapacitorNativeConfig.httpEnabled === true;
} else if (platform === 'android' && typeof win.CapacitorHttpAndroidInterface !== 'undefined') {
doPatchHttp = win.CapacitorHttpAndroidInterface.isEnabled() === true;
}

if (doPatchHttp) {
Expand Down
49 changes: 49 additions & 0 deletions core/src/tests/bridge.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,55 @@ describe('bridge', () => {
});
});

it('android patches fetch when CapacitorNativeConfig.httpEnabled is true without CapacitorHttpAndroidInterface', () => {
const originalFetch = window.fetch;
const originalXHR = window.XMLHttpRequest;
const stubFetch = jest.fn();
window.fetch = stubFetch;
try {
win.androidBridge = { postMessage: jest.fn() };
win.CapacitorNativeConfig = { cookiesEnabled: false, httpEnabled: true };
initBridge(win);
expect(window.fetch).not.toBe(stubFetch);
expect(win.CapacitorWebFetch).toBe(stubFetch);
} finally {
window.fetch = originalFetch;
window.XMLHttpRequest = originalXHR;
}
});

it('android does not patch fetch when CapacitorNativeConfig.httpEnabled is false', () => {
const originalFetch = window.fetch;
const originalXHR = window.XMLHttpRequest;
const stubFetch = jest.fn();
window.fetch = stubFetch;
try {
win.androidBridge = { postMessage: jest.fn() };
win.CapacitorNativeConfig = { cookiesEnabled: false, httpEnabled: false };
win.CapacitorHttpAndroidInterface = { isEnabled: jest.fn(() => true) };
initBridge(win);
expect(window.fetch).toBe(stubFetch);
expect(win.CapacitorHttpAndroidInterface.isEnabled).not.toHaveBeenCalled();
} finally {
window.fetch = originalFetch;
window.XMLHttpRequest = originalXHR;
}
});

it('android keeps browser document.cookie working when CapacitorCookiesAndroidInterface is absent', () => {
try {
win.androidBridge = { postMessage: jest.fn() };
win.CapacitorNativeConfig = { cookiesEnabled: true, httpEnabled: false };

initBridge(win);

document.cookie = 'cap_test=1';
expect(document.cookie).toContain('cap_test=1');
} finally {
document.cookie = 'cap_test=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
}
});

const mockAndroidPluginResult = (pluginResult: PluginResult) => {
win.androidBridge = {
postMessage: (m) => {
Expand Down
Loading