### Check WebView2 Runtime Availability Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Check if the WebView2 Runtime is installed on the user's machine. Returns the version string if available, otherwise null. If not installed, it provides a link to the download page. ```dart import 'package:webview_windows/webview_windows.dart'; import 'package:url_launcher/url_launcher.dart'; Future ensureWebView2() async { final version = await WebviewController.getWebViewVersion(); if (version == null) { // Runtime not found – send user to download page await launchUrl(Uri.parse( 'https://developer.microsoft.com/en-us/microsoft-edge/webview2/')); } else { debugPrint('WebView2 Runtime version: $version'); // e.g. "109.0.1518.78" } } ``` -------------------------------- ### WebviewController.getWebViewVersion Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt A static helper method to check for the availability of the WebView2 Runtime. It returns the browser version string if the runtime is installed, or null if it is not. This is useful for redirecting users to the download page if the runtime is missing. ```APIDOC ## WebviewController.getWebViewVersion ### Description A static helper that returns the browser version string (including channel name when not the stable Runtime). Returns `null` if the WebView2 Runtime is not installed, allowing you to redirect users to the download page before attempting to create a WebView. ### Method `WebviewController.getWebViewVersion` ### Response #### Success Response - **version** (string | null) - The WebView2 Runtime version string, or null if not installed. ### Request Example ```dart import 'package:webview_windows/webview_windows.dart'; import 'package:url_launcher/url_launcher.dart'; Future ensureWebView2() async { final version = await WebviewController.getWebViewVersion(); if (version == null) { // Runtime not found – send user to download page await launchUrl(Uri.parse( 'https://developer.microsoft.com/en-us/microsoft-edge/webview2/')); } else { debugPrint('WebView2 Runtime version: $version'); // e.g. "109.0.1518.78" } } ``` ``` -------------------------------- ### Inject Persistent Scripts into WebView Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Registers JavaScript to be injected before page scripts run. Useful for polyfills or SDK setup. Returns a ScriptID for later removal. ```dart // Inject a bridge object before page scripts execute final scriptId = await _controller.addScriptToExecuteOnDocumentCreated(''' window.__nativeBridge = { appVersion: "1.2.3", platform: "windows", sendMessage: (msg) => window.chrome.webview.postMessage(msg) }; '''); debugPrint('Registered script: $scriptId'); ``` ```dart // Later, remove it if no longer needed if (scriptId != null) { await _controller.removeScriptToExecuteOnDocumentCreated(scriptId); } ``` -------------------------------- ### Create and Initialize WebView Instance Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Allocate the native WebView2 instance and set up platform textures and channels. This must be awaited before using other controller methods. After completion, the controller is initialized and ready. ```dart class _BrowserState extends State { final _controller = WebviewController(); @override void initState() { super.initState(); _initWebView(); } Future _initWebView() async { try { await _controller.initialize(); await _controller.loadUrl('https://flutter.dev'); setState(() {}); } on PlatformException catch (e) { debugPrint('WebView init failed: ${e.message}'); } } @override Widget build(BuildContext context) { return _controller.value.isInitialized ? Webview(_controller) : const CircularProgressIndicator(); } @override void dispose() { _controller.dispose(); super.dispose(); } } ``` -------------------------------- ### WebviewController.initialize Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Creates and initializes a WebView instance, allocating the native WebView2 instance and setting up platform textures and communication channels. This method must be awaited before any other controller methods can be called. After completion, `controller.value.isInitialized` will be true. ```APIDOC ## WebviewController.initialize ### Description Allocates the native WebView2 instance and sets up the platform texture and event/method channels. Must be awaited before calling any other controller method. After it completes, `controller.value.isInitialized` becomes `true` and the `ready` future resolves. ### Method `WebviewController.initialize` ### Request Example ```dart class _BrowserState extends State { final _controller = WebviewController(); @override void initState() { super.initState(); _initWebView(); } Future _initWebView() async { try { await _controller.initialize(); await _controller.loadUrl('https://flutter.dev'); setState(() {}); } on PlatformException catch (e) { debugPrint('WebView init failed: ${e.message}'); } } @override Widget build(BuildContext context) { return _controller.value.isInitialized ? Webview(_controller) : const CircularProgressIndicator(); } @override void dispose() { _controller.dispose(); super.dispose(); } } ``` ``` -------------------------------- ### WebviewController.initializeEnvironment Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Optionally configure the shared WebView2 environment once before creating any WebviewController instances. This allows customization of the user data path, specifying an Edge browser executable, and passing additional Chromium command-line arguments. It must be called before the first WebviewController.initialize(). ```APIDOC ## WebviewController.initializeEnvironment ### Description Optionally called once before any `WebviewController` is created to customise the shared WebView2 environment. Accepts a custom user-data directory, a path to a specific Edge browser executable, and raw Chromium command-line flags. Must be called before the first `WebviewController.initialize()`. ### Method `WebviewController.initializeEnvironment` ### Parameters #### Path Parameters - **userDataPath** (string) - Optional - A custom path for user data. - **additionalArguments** (string) - Optional - Raw Chromium command-line flags. ### Request Example ```dart import 'package:webview_windows/webview_windows.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); // Custom profile directory + enable the FPS counter via Chromium flag await WebviewController.initializeEnvironment( userDataPath: r'C:\MyApp\WebData', additionalArguments: '--show-fps-counter --disable-web-security', ); runApp(const MyApp()); } ``` ``` -------------------------------- ### Initialize WebView2 Environment Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Optionally configure the shared WebView2 environment before creating any WebView instances. This allows setting a custom user-data directory and passing additional Chromium command-line arguments. Must be called before the first WebviewController.initialize(). ```dart import 'package:webview_windows/webview_windows.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); // Custom profile directory + enable the FPS counter via Chromium flag await WebviewController.initializeEnvironment( userDataPath: r'C:\MyApp\WebData', additionalArguments: '--show-fps-counter --disable-web-security', ); runApp(const MyApp()); } ``` -------------------------------- ### Apply Standard Settings and Compile Definitions Source: https://github.com/jnschulze/flutter-webview-windows/blob/main/example/windows/runner/CMakeLists.txt Applies standard build settings and defines NOMINMAX to prevent conflicts with Windows headers. ```cmake apply_standard_settings(${BINARY_NAME}) target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") ``` -------------------------------- ### Serve local files via hostname with `addVirtualHostNameMapping` Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Map a virtual hostname to a local folder to serve assets using `https://` URLs. Use `removeVirtualHostNameMapping` to unmap the hostname later. Ensure the `accessKind` is set appropriately for cross-origin resource access. ```dart // Serve local assets at https://my-app.local/ await _controller.addVirtualHostNameMapping( 'my-app.local', r'C:\MyApp\assets\web', WebviewHostResourceAccessKind.allow, ); await _controller.loadUrl('https://my-app.local/index.html'); // Later, remove the mapping await _controller.removeVirtualHostNameMapping('my-app.local'); ``` -------------------------------- ### Navigation Methods Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Methods for navigating the WebView, including loading URLs, loading HTML strings, going back/forward, reloading, and stopping the current page load. ```APIDOC ## Navigation Methods ### Description `loadUrl` navigates the WebView to the given URL. `loadStringContent` loads an arbitrary HTML string directly into the WebView without a network request, useful for displaying generated content or local templates. Standard browser navigation methods like `goBack`, `goForward`, `reload`, and `stop` are also available. Use the `historyChanged` stream to enable or disable back/forward buttons reactively. ### Usage Examples ```dart // Navigate to a URL await _controller.loadUrl('https://example.com'); // Load a locally-generated HTML document await _controller.loadStringContent(''' Hello

Embedded content

Rendered inside Flutter on Windows.

'''); // Listen to history state _controller.historyChanged.listen((state) { setState(() { _canGoBack = state.canGoBack; _canGoForward = state.canGoForward; }); }); // Wire up UI buttons Row(children: [ IconButton( icon: const Icon(Icons.arrow_back), onPressed: _canGoBack ? _controller.goBack : null, ), IconButton( icon: const Icon(Icons.arrow_forward), onPressed: _canGoForward ? _controller.goForward : null, ), IconButton( icon: const Icon(Icons.refresh), onPressed: _controller.reload, ), IconButton( icon: const Icon(Icons.stop), onPressed: _controller.stop, ), ]) ``` ``` -------------------------------- ### Handle Download Events Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Listens for download events from the WebView, specifically tracking download progress. It prints the percentage of the download when the event kind is 'downloadProgress'. ```dart // Download events _controller.onDownloadEvent.listen((event) { if (event.kind == WebviewDownloadEventKind.downloadProgress) { final pct = (event.bytesReceived / event.totalBytesToReceive * 100).round(); debugPrint('Download ${event.url}: $pct%'); } }); ``` -------------------------------- ### Control popup window behavior with `setPopupWindowPolicy` Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Configure how `window.open()` and link-target popups are handled. `deny` suppresses them, `allow` creates new OS windows, and `sameWindow` loads popups within the current WebView. ```dart // Suppress all popups (recommended for kiosk-style apps) await _controller.setPopupWindowPolicy(WebviewPopupWindowPolicy.deny); // Redirect popup content into the same WebView await _controller.setPopupWindowPolicy(WebviewPopupWindowPolicy.sameWindow); ``` -------------------------------- ### addVirtualHostNameMapping / removeVirtualHostNameMapping Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Allows serving local files using a virtual hostname with an HTTPS URL, instead of file paths. This mapping can be removed later. ```APIDOC ## `addVirtualHostNameMapping` / `removeVirtualHostNameMapping` — Serve local files via a hostname Maps a virtual hostname to a local folder so the WebView can load local assets using a normal `https://` URL instead of `file://` paths. The `accessKind` controls cross-origin resource access. ### Method `addVirtualHostNameMapping(String hostname, String folderPath, WebviewHostResourceAccessKind accessKind)` `removeVirtualHostNameMapping(String hostname)` ### Parameters - **hostname** (string) - The virtual hostname to map (e.g., 'my-app.local'). - **folderPath** (string) - The local file system path to the folder containing assets. - **accessKind** (WebviewHostResourceAccessKind) - Controls cross-origin resource access. ### Request Example ```dart await _controller.addVirtualHostNameMapping( 'my-app.local', r'C:\MyApp\assets\web', WebviewHostResourceAccessKind.allow, ); await _controller.loadUrl('https://my-app.local/index.html'); // Later, remove the mapping await _controller.removeVirtualHostNameMapping('my-app.local'); ``` ``` -------------------------------- ### openDevTools Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Launches the Edge DevTools panel in a separate window for the current WebView. This is particularly useful during development and debugging phases. ```APIDOC ## `openDevTools` — Launch the Edge DevTools panel Opens the Chromium DevTools in a separate window for the current WebView. Useful during development and debugging. ```dart IconButton( icon: const Icon(Icons.developer_mode), tooltip: 'Open DevTools', onPressed: _controller.openDevTools, ) ``` ``` -------------------------------- ### Open DevTools for WebView Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Launches the Chromium DevTools in a separate window for the current WebView. This is useful during development and debugging. ```dart IconButton( icon: const Icon(Icons.developer_mode), tooltip: 'Open DevTools', onPressed: _controller.openDevTools, ) ``` -------------------------------- ### Webview Widget Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt The Webview widget renders the WebView2 instance and handles user input. It accepts optional width, height, scaleFactor, filterQuality, and a permissionRequested callback. ```APIDOC ## Webview Widget ### Description The `Webview` widget renders the GPU texture produced by the native WebView2 instance and handles all mouse, touch, trackpad, and scroll input automatically. It accepts optional `width`/`height` constraints (defaults to expanding to fill available space), a `scaleFactor` override for DPI control, a `filterQuality` for texture scaling, and a `permissionRequested` callback. ### Usage Example ```dart Webview( _controller, width: 800, height: 600, filterQuality: FilterQuality.medium, // smooth downscaling permissionRequested: (url, kind, isUserInitiated) async { // kind: WebviewPermissionKind.camera, .microphone, .geoLocation, etc. final allow = await showDialog( context: context, builder: (_) => AlertDialog( title: Text('Permission Request'), content: Text('$url wants access to $kind'), actions: [ TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Deny')), TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('Allow')), ], ), ); return allow == true ? WebviewPermissionDecision.allow : WebviewPermissionDecision.deny; }, ) ``` ``` -------------------------------- ### Link Libraries and Include Directories Source: https://github.com/jnschulze/flutter-webview-windows/blob/main/example/windows/runner/CMakeLists.txt Links the necessary Flutter libraries and includes the source directory for header resolution. ```cmake target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### Navigate WebView Content Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Load content into the WebView by URL or by an HTML string. Useful for displaying external websites or locally generated HTML. ```dart // Navigate to a URL await _controller.loadUrl('https://example.com'); ``` ```dart // Load a locally-generated HTML document await _controller.loadStringContent(''' Hello

Embedded content

Rendered inside Flutter on Windows.

'''); ``` -------------------------------- ### Script Execution Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Execute arbitrary JavaScript in the WebView and retrieve the result, or inject persistent scripts that run on document creation. ```APIDOC ## Script Execution ### Description `executeScript` runs an arbitrary JavaScript expression in the top-level document and returns the JSON-decoded result. It returns `null` if the WebView is disposed or the script returns `undefined`. `addScriptToExecuteOnDocumentCreated` registers JavaScript to be injected into every page before any page scripts run, useful for polyfills or SDK setup. It returns a `ScriptID` that can be passed to `removeScriptToExecuteOnDocumentCreated` to unregister the script. ### Usage Examples ```dart // Read the page title via JS final title = await _controller.executeScript('document.title'); debugPrint('Page title: $title'); // e.g. "Flutter - Beautiful native apps" // Perform a DOM mutation and check a value final count = await _controller.executeScript(''' (() => { document.querySelectorAll('a').forEach(a => a.style.color = 'red'); return document.querySelectorAll('a').length; })() '''); debugPrint('Links recolored: $count'); // Inject a bridge object before page scripts execute final scriptId = await _controller.addScriptToExecuteOnDocumentCreated(''' window.__nativeBridge = { appVersion: "1.2.3", platform: "windows", sendMessage: (msg) => window.chrome.webview.postMessage(msg) }; '''); debugPrint('Registered script: $scriptId'); // Later, remove it if no longer needed if (scriptId != null) { await _controller.removeScriptToExecuteOnDocumentCreated(scriptId); } ``` ``` -------------------------------- ### setFpsLimit Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Limits the rendering frame rate of the WebView to reduce GPU load. A value of 0 removes the limit. ```APIDOC ## `setFpsLimit` — Limit rendering frame rate Caps the WebView's rendering frame rate to the given value to reduce GPU load. Pass `0` (or omit the argument) to remove any limit. ### Method `setFpsLimit(int fps)` ### Parameters - **fps** (int) - The maximum frames per second to render. `0` means no limit. ### Request Example ```dart // Cap at 30 FPS to save resources await _controller.setFpsLimit(30); // Uncap (default) await _controller.setFpsLimit(0); ``` ``` -------------------------------- ### Limit rendering frame rate with `setFpsLimit` Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Cap the WebView's rendering frame rate to reduce GPU load. Pass `0` or omit the argument to remove any limit. Use `setFpsLimit(30)` to cap at 30 FPS or `setFpsLimit(0)` to uncap. ```dart // Cap at 30 FPS to save resources await _controller.setFpsLimit(30); // Uncap (default) await _controller.setFpsLimit(0); ``` -------------------------------- ### WebView Navigation Controls Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Provides standard browser navigation methods like go back, go forward, reload, and stop. Use the `historyChanged` stream to manage UI element states. ```dart // Listen to history state _controller.historyChanged.listen((state) { setState(() { _canGoBack = state.canGoBack; _canGoForward = state.canGoForward; }); }); ``` ```dart // Wire up UI buttons Row(children: [ IconButton( icon: const Icon(Icons.arrow_back), onPressed: _canGoBack ? _controller.goBack : null, ), IconButton( icon: const Icon(Icons.arrow_forward), onPressed: _canGoForward ? _controller.goForward : null, ), IconButton( icon: const Icon(Icons.refresh), onPressed: _controller.reload, ), IconButton( icon: const Icon(Icons.stop), onPressed: _controller.stop, ), ]) ``` -------------------------------- ### suspend / resume Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Allows pausing and resuming the WebView's script execution and rendering to reduce resource consumption when the view is not active. ```APIDOC ## `suspend` / `resume` — Pause and resume the WebView Suspending the WebView halts script execution and rendering, reducing CPU and GPU usage when the view is off-screen or the application is idle. Resuming restores normal operation. ### Methods - `suspend()` - `resume()` ### Request Example ```dart // Pause when window is minimized await _controller.suspend(); // Resume when window is restored await _controller.resume(); ``` ``` -------------------------------- ### Define Flutter Windows Runner Executable Source: https://github.com/jnschulze/flutter-webview-windows/blob/main/example/windows/runner/CMakeLists.txt Configures the main executable for the Windows runner, listing all source files and resources required for the application. ```cmake cmake_minimum_required(VERSION 3.15) project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) ``` -------------------------------- ### Embed WebView Widget in Flutter Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Renders the WebView and handles input. Accepts optional width, height, and a permission requested callback. ```dart Webview( _controller, width: 800, height: 600, filterQuality: FilterQuality.medium, // smooth downscaling permissionRequested: (url, kind, isUserInitiated) async { // kind: WebviewPermissionKind.camera, .microphone, .geoLocation, etc. final allow = await showDialog( context: context, builder: (_) => AlertDialog( title: Text('Permission Request'), content: Text('$url wants access to $kind'), actions: [ TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Deny')), TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('Allow')), ], ), ); return allow == true ? WebviewPermissionDecision.allow : WebviewPermissionDecision.deny; }, ) ``` -------------------------------- ### Loading Indicator with StreamBuilder Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Shows a linear progress indicator while the WebView is loading content. It hides when loading is complete, using StreamBuilder to monitor the loading state. ```dart // Loading indicator StreamBuilder( stream: _controller.loadingState, builder: (context, snapshot) { if (snapshot.data == LoadingState.loading) { return const LinearProgressIndicator(); } return const SizedBox.shrink(); }, ) ``` -------------------------------- ### Pause and resume WebView with `suspend` and `resume` Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Halt script execution and rendering by suspending the WebView to reduce resource usage when off-screen or idle. Resume the WebView to restore normal operation. ```dart // Pause when window is minimized await _controller.suspend(); // Resume when window is restored await _controller.resume(); ``` -------------------------------- ### setPopupWindowPolicy Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Configures how the WebView handles popup window requests, such as those generated by `window.open()`. ```APIDOC ## `setPopupWindowPolicy` — Control popup window behavior Configures how the WebView handles `window.open()` and link-target popup requests. `deny` suppresses them, `allow` creates new OS windows, and `sameWindow` loads popup content in the current WebView. ### Method `setPopupWindowPolicy(WebviewPopupWindowPolicy policy)` ### Parameters - **policy** (WebviewPopupWindowPolicy) - The policy for handling popups. Options include `deny`, `allow`, and `sameWindow`. ### Request Example ```dart // Suppress all popups (recommended for kiosk-style apps) await _controller.setPopupWindowPolicy(WebviewPopupWindowPolicy.deny); // Redirect popup content into the same WebView await _controller.setPopupWindowPolicy(WebviewPopupWindowPolicy.sameWindow); ``` ``` -------------------------------- ### setUserAgent Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Allows overriding the default user-agent string sent by the WebView. This is useful for identifying the application or for services that serve content based on the user-agent. ```APIDOC ## `setUserAgent` — Override the browser user-agent string Replaces the default WebView2 user-agent with a custom string. Useful when a remote service serves different content based on the UA, or when you want to identify your application. ### Method `setUserAgent(String userAgent)` ### Parameters - **userAgent** (string) - The custom user-agent string to set. ### Request Example ```dart await _controller.setUserAgent( 'MyFlutterApp/1.0 (Windows NT 10.0) WebView2', ); ``` ``` -------------------------------- ### Manage cache and cookies with `clearCookies`, `clearCache`, `setCacheDisabled` Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Programmatically clear stored cookies or HTTP cache, or toggle cache usage. Useful for sign-out flows, testing, or forcing fresh content loads. Use `setCacheDisabled(true)` to disable cache and `setCacheDisabled(false)` to re-enable it. ```dart // Sign-out: clear cookies and cache await _controller.clearCookies(); await _controller.clearCache(); // Disable cache for the lifetime of this session await _controller.setCacheDisabled(true); // Re-enable cache await _controller.setCacheDisabled(false); ``` -------------------------------- ### Handle Full-Screen Element Changes Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Listens for changes in whether the WebView contains a full-screen element, such as a video. It then synchronizes the native window's full-screen state accordingly. ```dart // Full-screen video / element transitions _controller.containsFullScreenElementChanged.listen((isFullScreen) { windowManager.setFullScreen(isFullScreen); }); ``` -------------------------------- ### Programmatic zoom control with `setZoomFactor` Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Set the page zoom level, where `1.0` is 100% and `2.0` is 200%. Use `setZoomFactor(1.5)` to zoom in to 150% or `setZoomFactor(1.0)` to reset to normal zoom. ```dart // Zoom in to 150% await _controller.setZoomFactor(1.5); // Reset to normal zoom await _controller.setZoomFactor(1.0); ``` -------------------------------- ### Handle WebView Navigation Errors Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Listens for navigation errors and prints the error status. Useful for implementing custom error handling logic, such as displaying an error message to the user. ```dart // Navigation error handling _controller.onLoadError.listen((WebErrorStatus status) { debugPrint('Navigation failed: $status'); // e.g. WebErrorStatus.WebErrorStatusHostNameNotResolved }); ``` -------------------------------- ### Add Flutter Assemble Dependency Source: https://github.com/jnschulze/flutter-webview-windows/blob/main/example/windows/runner/CMakeLists.txt Ensures that the Flutter assembly target is built before the runner executable. ```cmake add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### Execute JavaScript in WebView Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Runs JavaScript in the WebView and returns the JSON-decoded result. Useful for interacting with the web content or retrieving data. ```dart // Read the page title via JS final title = await _controller.executeScript('document.title'); debugPrint('Page title: $title'); // e.g. "Flutter - Beautiful native apps" ``` ```dart // Perform a DOM mutation and check a value final count = await _controller.executeScript(''' (() => { document.querySelectorAll('a').forEach(a => a.style.color = 'red'); return document.querySelectorAll('a').length; })() '''); debugPrint('Links recolored: $count'); ``` -------------------------------- ### clearCookies / clearCache / setCacheDisabled Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Provides methods to manage the WebView's cache and cookies, including clearing them or disabling caching entirely. ```APIDOC ## `clearCookies` / `clearCache` / `setCacheDisabled` — Cache and cookie management Programmatically clear stored cookies or the HTTP cache, or toggle cache usage entirely. Useful for sign-out flows, testing, or forcing fresh content loads. ### Methods - `clearCookies()` - `clearCache()` - `setCacheDisabled(bool disabled)` ### Parameters - **disabled** (bool) - When `true`, disables the cache; when `false`, re-enables it. ### Request Example ```dart // Sign-out: clear cookies and cache await _controller.clearCookies(); await _controller.clearCache(); // Disable cache for the lifetime of this session await _controller.setCacheDisabled(true); // Re-enable cache await _controller.setCacheDisabled(false); ``` ``` -------------------------------- ### Event Streams Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt React to WebView state changes using broadcast streams exposed by `WebviewController`. These streams can be consumed using `StreamBuilder` widgets or `listen` subscriptions to keep the native Flutter UI in sync with the embedded web content. ```APIDOC ## Event streams — React to WebView state changes `WebviewController` exposes several broadcast streams for observing WebView state. These can be consumed with `StreamBuilder` widgets or `listen` subscriptions. ```dart // URL bar that updates as the user navigates StreamBuilder( stream: _controller.url, builder: (context, snapshot) => Text(snapshot.data ?? ''), ), // Loading indicator StreamBuilder( stream: _controller.loadingState, builder: (context, snapshot) { if (snapshot.data == LoadingState.loading) { return const LinearProgressIndicator(); } return const SizedBox.shrink(); }, ), // Page title in the window/app-bar StreamBuilder( stream: _controller.title, builder: (context, snapshot) => Text(snapshot.data ?? 'My Browser'), ), // Navigation error handling _controller.onLoadError.listen((WebErrorStatus status) { debugPrint('Navigation failed: $status'); // e.g. WebErrorStatus.WebErrorStatusHostNameNotResolved }), // Full-screen video / element transitions _controller.containsFullScreenElementChanged.listen((isFullScreen) { windowManager.setFullScreen(isFullScreen); }), // Download events _controller.onDownloadEvent.listen((event) { if (event.kind == WebviewDownloadEventKind.downloadProgress) { final pct = (event.bytesReceived / event.totalBytesToReceive * 100).round(); debugPrint('Download ${event.url}: $pct%'); } }), ``` ``` -------------------------------- ### Override user-agent string with `setUserAgent` Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Replace the default WebView2 user-agent string with a custom one. This is useful when a remote service serves different content based on the UA or to identify your application. ```dart await _controller.setUserAgent( 'MyFlutterApp/1.0 (Windows NT 10.0) WebView2', ); ``` -------------------------------- ### URL Bar Updates with StreamBuilder Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Displays the current URL of the WebView and updates automatically as the user navigates. Uses StreamBuilder to react to URL changes. ```dart // URL bar that updates as the user navigates StreamBuilder( stream: _controller.url, builder: (context, snapshot) => Text(snapshot.data ?? ''), ) ``` -------------------------------- ### Set WebView background color with `setBackgroundColor` Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Set the background color behind web content. Transparent is supported, and non-zero alpha values are treated as opaque. It's recommended to set this before loading a page to prevent a white flash. ```dart // Transparent background so Flutter widgets show through await _controller.setBackgroundColor(Colors.transparent); // Dark background matching a dark-mode theme await _controller.setBackgroundColor(const Color(0xFF1E1E1E)); ``` -------------------------------- ### Bi-directional Dart ↔ JS messaging with `postWebMessage` Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Listen for messages from the web page using the `webMessage` stream and send messages to the web page using `postWebMessage`. Ensure messages are JSON-encoded when sending from Dart. ```dart // 1. Listen for messages coming FROM the web page _controller.webMessage.listen((message) { debugPrint('From JS: $message'); // already JSON-decoded if (message is Map && message['type'] == 'buttonClicked') { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Web button clicked: ${message['id']}')), ); } }); // 2. Load a page that posts messages back to Flutter await _controller.loadStringContent(''' '''); // 3. Send a message TO the web page from Dart import 'dart:convert'; await _controller.postWebMessage(jsonEncode({'type': 'init', 'token': 'abc123'})); ``` -------------------------------- ### Page Title Updates with StreamBuilder Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Displays the current page title in the app bar or window title. Updates dynamically using StreamBuilder to reflect changes from the WebView. ```dart // Page title in the window/app-bar StreamBuilder( stream: _controller.title, builder: (context, snapshot) => Text(snapshot.data ?? 'My Browser'), ) ``` -------------------------------- ### setZoomFactor Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Programmatically controls the zoom level of the web content displayed in the WebView. ```APIDOC ## `setZoomFactor` — Programmatic zoom control Sets the page zoom level, where `1.0` is 100% (normal), `2.0` is 200%, etc. ### Method `setZoomFactor(double factor)` ### Parameters - **factor** (double) - The zoom factor. `1.0` is normal size. ### Request Example ```dart // Zoom in to 150% await _controller.setZoomFactor(1.5); // Reset to normal zoom await _controller.setZoomFactor(1.0); ``` ``` -------------------------------- ### postWebMessage / webMessage stream Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Enables bi-directional messaging between Dart and JavaScript. Dart can send JSON strings to the web page, and the web page can send messages back to Dart via a stream. ```APIDOC ## `postWebMessage` / `webMessage` stream — Bi-directional Dart ↔ JS messaging `postWebMessage` sends a JSON string from Dart to the page. The page receives it via `window.chrome.webview.addEventListener('message', ...)`. Conversely, when the page calls `window.chrome.webview.postMessage(data)`, the `webMessage` stream emits the JSON-decoded value. ### Method Dart: `postWebMessage(String jsonString)` JavaScript: `window.chrome.webview.postMessage(data)` ### Event Listener (JavaScript) ```javascript window.chrome.webview.addEventListener('message', (event) => { // Handle message from Dart }); ``` ### Stream Listener (Dart) ```dart _controller.webMessage.listen((message) { // Handle message from JavaScript }); ``` ### Request Example (Dart to JS) ```dart import 'dart:convert'; await _controller.postWebMessage(jsonEncode({'type': 'init', 'token': 'abc123'})); ``` ### Request Example (JS to Dart) ```javascript window.chrome.webview.postMessage(JSON.stringify({type:'buttonClicked',id:'btn1'})); ``` ``` -------------------------------- ### setBackgroundColor Source: https://context7.com/jnschulze/flutter-webview-windows/llms.txt Sets the background color of the WebView. Supports transparent colors to allow Flutter widgets to show through. ```APIDOC ## `setBackgroundColor` — Set the WebView background color Sets the background color rendered behind the web content. Transparent (`Colors.transparent`) is supported (alpha = 0); any other non-zero alpha is treated as fully opaque. Commonly set before loading a page to avoid a white flash. ### Method `setBackgroundColor(Color color)` ### Parameters - **color** (Color) - The color to set as the background. ### Request Example ```dart // Transparent background so Flutter widgets show through await _controller.setBackgroundColor(Colors.transparent); // Dark background matching a dark-mode theme await _controller.setBackgroundColor(const Color(0xFF1E1E1E)); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.