Skip to content

The JavaScript Bridge Global and Handler Wiring

Every conversation between a web page and your Flutter code inside this plugin travels through a single injected JavaScript global: window.zikzak_inappwebview, and specifically its one method callHandler. This page explains what that global is, how a message makes the round trip from JavaScript to Dart and back, how you register the Dart half of the conversation, and how each platform implementation wires the two halves together. It is deliberately narrow: the widget and controller surface lives in InAppWebView Widget and InAppWebViewController, and the passkey bridge that reuses this channel is covered in WebAuthn and Passkey Bridge.

Sources: platform_inappwebview_controller.dart

The bridge is defined once, as documentation on the platform-interface method addJavaScriptHandler, and every platform implementation is expected to honour it. Three sentences of that contract carry the whole design: the JavaScript side calls window.zikzak_inappwebview.callHandler(handlerName, ...args); the args are stringified with JSON.stringify and decoded on the Dart side; and whatever your Dart callback returns is JSON-encoded back and becomes the resolution value of the JavaScript Promise that callHandler returned. Because callHandler returns a Promise, the bridge is request/response, not fire-and-forget — even when your callback returns nothing.

The Dart type at the other end is deliberately minimal: a JavaScriptHandlerCallback is just dynamic Function(List<dynamic> arguments), receiving the decoded argument list and returning any JSON-encodable value. The same doc comment names the native primitives each platform uses underneath — addJavascriptInterface on Android and addScriptMessageHandler on Apple platforms — which is the first hint that the bridge is a portability shim over three very different native message mechanisms.

Sources: javascript_handler_callback.dart, platform_inappwebview_controller.dart

The diagram below shows the Android/iOS/macOS path, which is the canonical one. Read it left to right: JavaScript calls the global, the native layer forwards the call to Dart over the existing platform method channel, the Dart handler map is consulted, and the return value is injected back into the page as a tiny script that resolves the pending promise by its numeric id.

sequenceDiagram
participant JS as Page JavaScript
participant G as window.zikzak_inappwebview
participant N as Native layer (Java / Swift / C++)
participant D as Dart platform controller
participant H as Your Dart callback
JS->>G: callHandler("myHandler", arg1, arg2)
G->>G: _callHandlerID = setTimeout(...)
G->>N: postMessage({handlerName, args: JSON.stringify(...), _callHandlerID, _windowId})
G-->>JS: returns pending Promise stored at bridge[_callHandlerID]
N->>D: method channel "onCallJsHandler"
D->>D: reserved-name switch, then _javaScriptHandlersMap lookup
D->>H: callback(List<dynamic> args)
H-->>D: return value (JSON-encodable)
D-->>N: jsonEncode(result)
N->>G: evaluateJavascript("bridge[_callHandlerID].resolve(json); delete ...")
G-->>JS: Promise resolves with decoded value

The JavaScript half of that sequence is generated natively and injected at document start, so it exists before any page script runs. On iOS the whole shim is a Swift string constant: it creates window.zikzak_inappwebview, stashes the resolve/reject pair under a timer-derived _callHandlerID, and posts the message through window.webkit.messageHandlers['callHandler']. The same file also defines the readiness event source, window.dispatchEvent(new Event('flutterInAppWebViewPlatformReady')), and declares the plugin script as required in all content worlds with messageHandlerNames: ["callHandler"].

Sources: JavaScriptBridgeJS.swift

Android mirrors this structure with a different transport. The bridge global name is a Java constant, and the plugin script is registered at document start; the actual transport is an @JavascriptInterface object exposed under that same name, so from JavaScript the injected object is the bridge. The reply is injected with evaluateJavascript (falling back to a javascript: URL on pre-KitKat), guarded by a null check so a page that navigated away mid-flight simply drops the reply.

Sources: JavaScriptBridgeJS.java, JavaScriptBridgeInterface.java

Registration is a three-method lifecycle: addJavaScriptHandler, hasJavaScriptHandler, and removeJavaScriptHandler. In the public API these live on the javaScript domain facade of the controller, which forwards each call straight to the platform controller; the monolith’s own top-level methods are thin aliases that route back through the same facade. For new code the facade form (controller.javaScript.addJavaScriptHandler(...)) is the one to prefer, since it groups all JavaScript-related operations in one place.

flowchart TD
A["controller.javaScript.addJavaScriptHandler(handlerName, callback)"] --> B["JavaScriptController (facade)"]
B --> C["PlatformInAppWebViewController<br/>(abstract contract)"]
C --> D["AndroidInAppWebViewController"]
C --> E["IOSInAppWebViewController"]
C --> F["MacOSInAppWebViewController"]
C --> G["Windows / Linux / OHOS / Web controllers"]
D --> H["_javaScriptHandlersMap[handlerName] = callback"]
E --> H
F --> H

Sources: javascript_controller.dart, in_app_webview_controller.dart, in_app_webview_controller.dart

Registration itself is pure Dart bookkeeping — no method channel call, no native round trip. Each platform controller keeps a Map<String, JavaScriptHandlerCallback> and addJavaScriptHandler writes into it after asserting the name is not reserved. That map is also what the keep-alive machinery saves and restores, which is why handlers survive a widget disposal/rebuild cycle when you use KeepAliveInAppWebView.

Sources: in_app_webview_controller.dart, in_app_webview_controller.dart, in_app_webview_keep_alive.dart

Ten names are already claimed by the plugin’s own internal traffic. Registering one of them trips an assertion in debug builds, because the internal switch runs before your handler map is consulted and your callback would silently never fire. The list is identical on Android, iOS, and macOS.

Reserved name Used for
onLoadResource Resource-load notifications
shouldInterceptAjaxRequest, onAjaxReadyStateChange, onAjaxProgress AJAX interception
shouldInterceptFetchRequest Fetch interception
onPrintRequest Print jobs
onWindowFocus, onWindowBlur Window focus events
callAsyncJavaScript callAsyncJavaScript result delivery
evaluateJavaScriptWithContentWorld Content-world evaluation results

Sources: in_app_webview_controller.dart, in_app_webview_controller.dart, JavaScriptBridgeInterface.java

Two more names are intercepted natively and never reach Dart at all: onInjectedScriptLoaded and onInjectedScriptError, which the native layers use to report that a script injected from a URL finished loading. The macOS Dart controller routes them to the registered script attributes before any user-handler lookup, explicitly so they cannot leak into the handler map.

Sources: in_app_webview_controller.dart, InAppWebView.swift

The injected script runs at document start, but the native end may not be attached yet. The contract therefore tells you to wait for the flutterInAppWebViewPlatformReady event before calling callHandler, and notes that from the onLoadStop event onward you can call it directly. Note the asymmetry introduced by the fork: the global was renamed but the event was not — you listen for flutterInAppWebViewPlatformReady while calling window.zikzak_inappwebview.callHandler.

window.addEventListener("flutterInAppWebViewPlatformReady", function (event) {
window.zikzak_inappwebview
.callHandler('handlerFooWithArgs', 1, true, ['bar', 5], { foo: 'baz' })
.then(function (result) { console.log(result); });
});

Each platform guards the dispatch so it fires exactly once and only in the top frame. Android and Linux check that the bridge object exists and that a _platformReady flag is unset before dispatching and then setting it; Windows and OpenHarmony dispatch unconditionally at the end of an idempotent IIFE; iOS emits it from the native side after injection.

Sources: platform_inappwebview_controller.dart, JavaScriptBridgeJS.java, javascript_bridge_js.h, in_app_webview_windows_controller.dart, ArkWebView.ets

Migrating from flutter_inappwebview: the Renamed Global

Section titled “Migrating from flutter_inappwebview: the Renamed Global”

This is the single most common source of confusion for newcomers arriving from upstream, and it is worth stating bluntly: the global is window.zikzak_inappwebview, not window.flutter_inappwebview. Nothing aliases the old name, so a leftover call fails with TypeError: Cannot read properties of undefined (reading 'callHandler') rather than a helpful error. The documentation-only nature of this gap is tracked as an open issue in the repository.

Upstream (flutter_inappwebview) This fork (zikzak_inappwebview) Action
window.flutter_inappwebview.callHandler(...) window.zikzak_inappwebview.callHandler(...) Rename in your page JS
flutterInAppWebViewPlatformReady event flutterInAppWebViewPlatformReady event No change

Sources: platform_inappwebview_controller.dart, issue.md

The same contract is implemented six ways. The table is the mental model to carry; the paragraphs after it explain the two design differences that actually matter.

Platform Transport Bridge installation Reply mechanism
Android addJavascriptInterface under the bridge name Deferred to View.post() after platform-view attach evaluateJavascript resolving bridge[_callHandlerID]
iOS / macOS WKScriptMessageHandler named callHandler Plugin script at document start, all content worlds Main-frame evaluateJavaScript resolving bridge[_callHandlerID]
Linux (WPE) webkit.messageHandlers['callHandler'] with-reply API, plus a bridge secret Plugin script, name configurable natively Native promise from postMessage
Windows (WebView2) chrome.webview.postMessage + webMessage stream addScriptToExecuteOnDocumentCreated, idempotent IIFE window._zikzakInAppWebViewResolveHandler(callId, ...)
OpenHarmony (ArkWeb) javaScriptProxy object __zikzakArkWeb Top-frame-only bridge IIFE __zikzakArkWebReply(documentId, callId, ...)
Web (iframe) window.postMessage Application-supplied page script Not returned to JS

Sources: InAppWebView.java, InAppWebView.swift, javascript_bridge_js.h, in_app_webview_windows_controller.dart, ArkWebView.ets, in_app_webview_web_controller.dart

Android defers registration on purpose. addJavascriptInterface and WebViewCompat.addDocumentStartJavaScript both perform binder IPC to the renderer process; running them synchronously inside the factory could cause the engine’s platform-view-created callback to be dropped. The registration is therefore posted to the view’s message queue, and each of the two risky calls gets its own try/catch (RuntimeException) with a log line, so an uncaught throw on the main looper cannot take down the app. A Dart-side source-contract test enforces that shape, since the Java cannot be executed on a Dart test host.

Sources: InAppWebView.java, js_bridge_registration_guard_contract_test.dart

Apple platforms register two handlers, not one. Alongside the legacy callHandler handler, macOS (and iOS where available) registers a reply-capable PasskeyBridge handler, because the legacy reply is a main-frame evaluateJavaScript that can never resolve a promise created inside a cross-origin iframe. The comment in the macOS source is explicit that the WithReply overload must be used: the plain overload registers an ordinary handler under which postMessage resolves undefined and the reply delegate is never reached. All messages that do arrive on callHandler are routed by _windowId, so a window.open child that shares the opener’s user content controller reaches the correct webview.

Sources: InAppWebView.swift, InAppWebView.swift

Windows and OpenHarmony use explicit call ids instead of a timer. Both generate a monotonically increasing callId, keep a pending map in the page, and resolve it from a dedicated global reply function. Neither returns a value to the JavaScript caller: Windows resolves with the JSON-parsed result, while the Web implementation simply invokes the Dart handler and ignores its return value.

Sources: in_app_webview_windows_controller.dart, ArkWebView.ets, in_app_webview_web_controller.dart

The bridge is not only for your code. Several advanced features are implemented as injected scripts that report through the very same callHandler channel, using reserved-looking __zikzak…__ names and a shared defensive pattern: resolve the bridge lazily, and if it is missing, buffer events in the page and flush them once Dart signals readiness.

Handler name Feature Injected script
__zikzakNavigationTracker__ History/URL change tracking navigation_tracker_js.dart
__zikzakNetworkCapture__ Network capture and interception network_capture_interceptor_js.dart
__zikzakRecipeTap__ Session recipe tap recording tap_listener_js.dart
__zikzakDialogueDismissed__ Dialogue dismisser dialogue_dismisser_js.dart
PasskeyBridge WebAuthn/passkey ceremonies passkeys_js_source.dart

The lazy bridge() helper in these scripts is the pattern to copy in your own injected code: probe for window.zikzak_inappwebview and a callable callHandler inside a try, and treat absence as “not ready yet” rather than an error. The Dart halves pair attach with detach — attach registers the handler and flushes the page queue, detach removes the handler — and both are idempotent per controller.

Sources: navigation_tracker_js.dart, navigation_tracker.dart, network_capture_manager.dart

Put the two halves side by side and the whole page becomes concrete. The Dart half registers on onWebViewCreated; the JavaScript half waits for readiness and calls through the global.

controller.addJavaScriptHandler(
handlerName: 'myHandler',
callback: (arguments) {
print('from JS: ${arguments.first}');
return {'pong': arguments.first}; // becomes the Promise resolution value
},
);
window.addEventListener('flutterInAppWebViewPlatformReady', function () {
window.zikzak_inappwebview
.callHandler('myHandler', 'ping')
.then(function (result) { console.log(result.pong); });
});

Sources: platform_inappwebview_controller.dart

If you want to see this exact round trip asserted without a device, the repository ships it as a GYM exercise: it boots a controller on a fake platform, registers a handler through the public javaScript facade, evaluates a real window.zikzak_inappwebview.callHandler(...) source, and asserts that the arguments crossed unchanged and the return value came back JSON-encoded. It is the cheapest way to confirm your mental model before touching a real WebView.

Sources: js_bridge_round_trip_test.dart

Symptom Likely cause Fix
TypeError: Cannot read properties of undefined (reading 'callHandler') Using the upstream global name Call window.zikzak_inappwebview.callHandler
Handler never fires, no error Registered after the page already called, or name is reserved Register in onWebViewCreated/onLoadStart; rename the handler
callHandler throws before load completes Called before flutterInAppWebViewPlatformReady Wrap the call in the readiness listener
Assertion "<name>" is a forbidden name! in debug Name collides with internal traffic Pick a different handlerName
Promise never settles in a cross-origin iframe (Apple) Legacy main-frame reply path Use the PasskeyBridge reply-capable handler for that traffic
Handler gone after widget rebuild Keep-alive not used Use KeepAliveInAppWebView, which persists the handler map

Sources: platform_inappwebview_controller.dart, in_app_webview_controller.dart, InAppWebView.swift, in_app_webview_keep_alive.dart

Now that the bridge is demystified, the natural next steps are the controller that owns it — InAppWebView Widget and InAppWebViewController — followed by the facade layout that groups these methods, in Domain Controller Facades: Navigation, JavaScript, Cookies, Settings. To see the bridge carrying real product traffic, read WebAuthn and Passkey Bridge and Network Capture, Interception, and Secret Redaction. If you came from upstream and want the full rename picture, Migrating from flutter_inappwebview is the companion page.