Skip to content
WebView AllWebView All
Documentation for version 1.4.x; select latest for up-to-date APIs.

JavaScript

JavaScript support is split into four areas: execution, return values, channels, and browser-style dialogs.

await controller.setJavaScriptMode(JavaScriptMode.unrestricted);

Disable JavaScript for untrusted content when your app does not need page scripting:

await controller.setJavaScriptMode(JavaScriptMode.disabled);

The web implementation applies a restrictive iframe sandbox when JavaScript is disabled and restores the configured sandbox when JavaScript is unrestricted.

await controller.runJavaScript('document.body.classList.add("ready")');
final value = await controller.runJavaScriptReturningResult(
'JSON.stringify({title: document.title})',
);

Return-value behavior:

PlatformReturn behavior
AndroidUses Android WebView evaluation result.
iOS/macOSUses WebKit evaluation; unsupported native values may throw.
WindowsUses WebView2 script execution and decodes returned values.
LinuxUses WebKitGTK and decodes JSON-marked results where needed.
OHOSUses ArkWeb evaluateJavascript; JSON is decoded when possible.
WebUses direct iframe eval for same-origin content and a source-validated message bridge for plugin-managed isolated HTML. Results must be JSON-serializable.

null and undefined are rejected by runJavaScriptReturningResult.

Use callAsyncJavaScript when the function body returns a Promise or needs structured named arguments:

final result = await controller.callAsyncJavaScript(
'''
const response = await fetch(endpoint);
return {status: response.status, body: await response.text()};
''',
arguments: <String, Object?>{
'endpoint': 'https://example.com/api',
},
timeout: const Duration(seconds: 15),
);

Argument names must be valid non-reserved JavaScript identifiers. Values are defensively copied and must contain only finite numbers, strings, booleans, null, lists, and string-keyed maps. Fulfilled values must be JSON-serializable; a thrown error or rejected Promise produces JavaScriptExecutionException, while expiration produces TimeoutException.

Android, iOS, macOS, Windows, Linux, and OHOS support this API. Web supports same-origin content and plugin-managed isolated HTML; direct cross-origin iframe pages remain inaccessible.

Register a provider or compatibility shim before loading the first page:

if (await controller.isUserScriptInjectionSupported(
WebViewUserScriptInjectionTime.documentStart,
)) {
final scriptId = await controller.addUserScript(
const WebViewUserScript(
source: 'globalThis.appProvider = Object.freeze({version: 1});',
forMainFrameOnly: true,
),
);
await controller.loadRequest(Uri.parse('https://example.com'));
// Later: await controller.removeUserScript(scriptId);
}

addUserScript must finish before navigation begins. Scripts execute in the same private function scope on every supported platform, so values intended for page code or another user script must be assigned explicitly to globalThis. This lexical scope is not a separate browser content world. Scripts apply to future documents and reloads; they do not retroactively run in the current document. removeAllUserScripts removes only scripts registered through this API and preserves plugin-managed channels and hooks.

PlatformDocument-start support
AndroidSupported when the installed Android System WebView exposes DOCUMENT_START_SCRIPT; check the capability at runtime.
iOS/macOSSupported by WKUserScript.
WindowsSupported by WebView2.
LinuxSupported by WebKitGTK.
OHOSSupported by ArkWeb; scripts run in registration order and can be registered before the widget is attached.
WebBrowser iframe APIs cannot guarantee execution before page scripts; capability returns false.
await controller.addJavaScriptChannel(
'Checkout',
onMessageReceived: (JavaScriptMessage message) {
debugPrint('Checkout event: ${message.message}');
},
);

Page JavaScript:

Checkout.postMessage(JSON.stringify({ type: 'loaded' }));

Remove a channel when it is no longer needed:

await controller.removeJavaScriptChannel('Checkout');

JavaScriptMessage reports the sending document URL (sourceUrl), browser security origin (sourceOrigin), and main-frame flag (isMainFrame) separately. Each field is nullable when the platform cannot reliably determine it. The string "null" in sourceOrigin means an opaque origin; Dart null means unknown.

PlatformsourceUrlsourceOriginisMainFrame
Android—When supportedWhen supported
iOS / macOSAvailableAvailableAvailable
WindowsAvailable—true (main document only)
LinuxAvailableAvailableAvailable
OHOSAvailable——
Web—Availabletrue (WebView main document only)

Android selects the implementation using the WebView’s message-listener and document-start script capabilities; older WebViews still deliver messages with unknown sender fields. Linux reads metadata in an isolated script world, so messages after pushState reflect the new URL. If the isolated relay is not ready, or the page calls a low-level message handler directly, delivery continues with unknown metadata. OHOS captures the document URL at the native proxy entry, but cannot reliably determine the security origin or frame identity.

Reject unknown senders for sensitive operations. Never substitute controller.currentUrl() for missing metadata or derive a security origin from sourceUrl: a sandboxed document can have an HTTPS URL and an opaque origin. This example accepts main-document messages from an allowed security origin; platforms without reliable origin information reject them:

await controller.addJavaScriptChannel(
'Checkout',
onMessageReceived: (JavaScriptMessage message) {
if (message.isMainFrame != true ||
message.sourceOrigin != 'https://shop.example.com') {
return;
}
debugPrint('Accepted checkout event: ${message.message}');
},
);
await controller.setOnConsoleMessage((JavaScriptConsoleMessage message) {
debugPrint('[${message.level.name}] ${message.message}');
});

Android, iOS, macOS, Windows, Linux, OHOS, and controllable Web content support console message callbacks.

await controller.setOnJavaScriptAlertDialog((request) async {
debugPrint('alert from ${request.url}: ${request.message}');
});
await controller.setOnJavaScriptConfirmDialog((request) async {
return request.message == 'Continue?';
});
await controller.setOnJavaScriptTextInputDialog((request) async {
return request.defaultText ?? '';
});

Dialog support by platform:

PlatformalertconfirmpromptNotes
AndroidSupportedSupportedSupportedNative WebChromeClient bridge.
iOS/macOSSupportedSupportedSupportedWebKit UI delegate bridge.
WindowsSupportedSupportedSupportedWebView2 JavaScript dialog bridge.
LinuxSupportedSupportedSupportedWebKitGTK dialog events.
OHOSSupportedSupportedSupportedArkWeb WebChromeClient bridge.
WebSame-origin or managed isolated HTMLSame-origin callback; isolated HTML keeps the browser dialogSame-origin callback; isolated HTML keeps the browser dialogCustom confirm and prompt callbacks must complete synchronously.

On web, confirm and prompt are browser-synchronous APIs. Return a SynchronousFuture from those callbacks if you need deterministic behavior for same-origin content:

await controller.setOnJavaScriptConfirmDialog((request) {
return SynchronousFuture<bool>(true);
});

Browser iframes block direct scripting of cross-origin pages. On web, these APIs require content that the host page can access:

  • runJavaScript
  • runJavaScriptReturningResult
  • callAsyncJavaScript
  • addJavaScriptChannel
  • setOnConsoleMessage
  • JavaScript dialog hooks
  • scroll position reads and writes

Use loadHtmlString, same-origin URLs, or fetch-backed loadRequest when you need those features in Flutter Web. Direct cross-origin iframe URLs remain inaccessible. Isolated HTML keeps browser-native confirm and prompt dialogs because synchronous callbacks cannot cross the frame boundary.