### Basic Web Authentication Session Example Source: https://inappwebview.dev/docs/web-authentication-session This snippet shows how to initialize the InAppLocalhostServer, create a WebAuthenticationSession, and handle the completion callback. It includes buttons to create, start, and dispose of the session. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; InAppLocalhostServer localhostServer = InAppLocalhostServer(); Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb) { await localhostServer.start(); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { final GlobalKey webViewKey = GlobalKey(); WebAuthenticationSession? session; String? token; @override void dispose() { session?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Web Authentication Session example')), body: Column(children: [ Center( child: Container( padding: const EdgeInsets.all(20.0), child: Text("Token: $token"), )), session != null ? Container() : Center( child: ElevatedButton( onPressed: () async { if (session == null && !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS && await WebAuthenticationSession.isAvailable()) { session = await WebAuthenticationSession.create( url: WebUri( "http://localhost:8080/assets/web-auth.html"), callbackURLScheme: "test", onComplete: (url, error) async { if (url != null) { setState(() { token = url.queryParameters["token"]; }); } }); setState(() {}); } else { ScaffoldMessenger.of(context) .showSnackBar(const SnackBar( content: Text( 'Cannot create Web Authentication Session!'), )); } }, child: const Text("Create Web Auth Session")), ), session == null ? Container() : Center( child: ElevatedButton( onPressed: () async { var started = false; if (await session?.canStart() ?? false) { started = await session?.start() ?? false; } if (!started) { ScaffoldMessenger.of(context) .showSnackBar(const SnackBar( content: Text( 'Cannot start Web Authentication Session!'), )); } }, child: const Text("Start Web Auth Session")), ), session == null ? Container() : Center( child: ElevatedButton( onPressed: () async { await session?.dispose(); setState(() { token = null; session = null; }); }, child: const Text("Dispose Web Auth Session")), ) ])); } } ``` -------------------------------- ### Run HeadlessInAppWebView to InAppWebView Conversion Source: https://inappwebview.dev/docs/webview/headless-in-app-webview This example demonstrates how to initialize and run a HeadlessInAppWebView, and then convert it into an InAppWebView widget. It includes setup for pull-to-refresh and event handlers for web view creation, load start, progress changes, and load stop. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { HeadlessInAppWebView? headlessWebView; PullToRefreshController? pullToRefreshController; InAppWebViewController? webViewController; String url = ""; int progress = 0; bool convertFlag = false; @override void initState() { super.initState(); pullToRefreshController = kIsWeb || ![TargetPlatform.iOS, TargetPlatform.android] .contains(defaultTargetPlatform) ? null : PullToRefreshController( settings: PullToRefreshSettings( color: Colors.blue, ), onRefresh: () async { if (defaultTargetPlatform == TargetPlatform.android) { webViewController?.reload(); } else if (defaultTargetPlatform == TargetPlatform.iOS) { webViewController?.loadUrl( urlRequest: URLRequest(url: await webViewController?.getUrl())); } }, ); headlessWebView = HeadlessInAppWebView( initialUrlRequest: URLRequest(url: WebUri("https://flutter.dev")), initialSettings: InAppWebViewSettings(isInspectable: kDebugMode), pullToRefreshController: pullToRefreshController, onWebViewCreated: (controller) { webViewController = controller; const snackBar = SnackBar( content: Text('HeadlessInAppWebView created!'), duration: Duration(seconds: 1), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); }, onLoadStart: (controller, url) async { setState(() { this.url = url?.toString() ?? ''; }); }, onProgressChanged: (controller, progress) { setState(() { this.progress = progress; }); }, onLoadStop: (controller, url) async { setState(() { this.url = url?.toString() ?? ''; }); }, ); } @override void dispose() { super.dispose(); headlessWebView?.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "HeadlessInAppWebView to InAppWebView", textScaleFactor: .8, )), body: Column(children: [ Container( padding: const EdgeInsets.all(20.0), child: Text( "URL: ".((url.length > 40) ? "${url.substring(0, 40)}..." : url) + " - " + progress.toString() + "%" ), ), !convertFlag ? Center( child: ElevatedButton( onPressed: () async { var headlessWebView = this.headlessWebView; if (headlessWebView != null && !headlessWebView.isRunning()) { await headlessWebView.run(); } }, child: const Text("Run HeadlessInAppWebView")), ) : Container(), !convertFlag ? Center( child: ElevatedButton( onPressed: () { if (!convertFlag) { ``` -------------------------------- ### Basic Context Menu Setup Source: https://inappwebview.dev/docs/webview/context-menu Demonstrates how to initialize and configure a ContextMenu with custom items and event handlers. This setup is used within a Flutter widget to manage the WebView's context menu. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { final GlobalKey webViewKey = GlobalKey(); InAppWebViewController? webViewController; InAppWebViewSettings settings = InAppWebViewSettings(isInspectable: kDebugMode); late ContextMenu contextMenu; @override void initState() { super.initState(); contextMenu = ContextMenu( menuItems: [ ContextMenuItem( id: 1, title: "Special", action: () async { const snackBar = SnackBar( content: Text("Special clicked!"), duration: Duration(seconds: 1), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); }) ], onCreateContextMenu: (hitTestResult) async { String selectedText = await webViewController?.getSelectedText() ?? ""; final snackBar = SnackBar( content: Text( "Selected text: '$selectedText', of type: ${hitTestResult.type.toString()}"), duration: const Duration(seconds: 1), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); }, onContextMenuActionItemClicked: (menuItem) { final snackBar = SnackBar( content: Text( "Menu item with ID ${menuItem.id} and title '${menuItem.title}' clicked!"), duration: const Duration(seconds: 1), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('ContextMenu Example'), ), body: Column(children: [ Expanded( child: InAppWebView( key: webViewKey, initialUrlRequest: URLRequest(url: WebUri("https://flutter.dev/")), contextMenu: contextMenu, initialSettings: settings, onWebViewCreated: (InAppWebViewController controller) { webViewController = controller; }, )), ])); } } ``` -------------------------------- ### Start and Configure InAppLocalhostServer Source: https://inappwebview.dev/docs/in-app-localhost-server This snippet demonstrates how to initialize and start the InAppLocalhostServer with a custom document root. It also includes the necessary setup for running a Flutter application with an InAppWebView. ```dart import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; final InAppLocalhostServer localhostServer = InAppLocalhostServer(documentRoot: 'assets'); Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb) { // start the localhost server await localhostServer.start(); } if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('InAppLocalhostServer Example'), ), body: Container( child: Column(children: [ Expanded( child: InAppWebView( initialSettings: InAppWebViewSettings( isInspectable: kDebugMode, ), initialUrlRequest: URLRequest(url: WebUri("http://localhost:8080/index.html")), onWebViewCreated: (controller) {}, onLoadStart: (controller, url) {}, onLoadStop: (controller, url) {}, ), ) ])), ); } } ``` -------------------------------- ### Basic WebViewAssetLoader Setup Source: https://inappwebview.dev/docs/webview/webview-asset-loader Configure WebViewAssetLoader with a basic AssetsPathHandler to load files from the '/assets/' directory. ```dart InAppWebViewSettings settings = InAppWebViewSettings( webViewAssetLoader: WebViewAssetLoader( pathHandlers: [ AssetsPathHandler(path: '/assets/') ] ) ); ``` -------------------------------- ### InAppBrowser Basic Usage Example Source: https://inappwebview.dev/docs/in-app-browsers/in-app-browser This example shows how to create a custom InAppBrowser class, override its event callbacks, and open a URL request. It includes setup for different platforms and basic InAppWebView settings. ```dart import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; WebViewEnvironment? webViewEnvironment; class MyInAppBrowser extends InAppBrowser { MyInAppBrowser({super.webViewEnvironment}); @override Future onBrowserCreated() async { print("Browser Created!"); } @override Future onLoadStart(url) async { print("Started $url"); } @override Future onLoadStop(url) async { print("Stopped $url"); } @override void onReceivedError(WebResourceRequest request, WebResourceError error) { print("Can't load ${request.url}.. Error: ${error.description}"); } @override void onProgressChanged(progress) { print("Progress: $progress"); } @override void onExit() { print("Browser closed!"); } } Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.windows) { final availableVersion = await WebViewEnvironment.getAvailableVersion(); assert(availableVersion != null, 'Failed to find an installed WebView2 Runtime or non-stable Microsoft Edge installation.'); webViewEnvironment = await WebViewEnvironment.create( settings: WebViewEnvironmentSettings(userDataFolder: 'YOUR_CUSTOM_PATH')); } if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp( const MaterialApp( home: MyApp(), ), ); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { final browser = MyInAppBrowser(webViewEnvironment: webViewEnvironment); final settings = InAppBrowserClassSettings( browserSettings: InAppBrowserSettings(hideUrlBar: false), webViewSettings: InAppWebViewSettings( javaScriptEnabled: true, isInspectable: kDebugMode)); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('InAppBrowser Example'), ), body: Center( child: ElevatedButton( onPressed: () { browser.openUrlRequest( urlRequest: URLRequest(url: WebUri("https://flutter.dev")), settings: settings); }, child: const Text("Open InAppBrowser")), ), ); } } ``` -------------------------------- ### Full Example: Print Job Controller Integration Source: https://inappwebview.dev/docs/webview/print-job-controller This example demonstrates how to integrate and use the PrintJobController within a Flutter application. It includes setting up the WebView, handling print requests, configuring print job settings, and managing the print job lifecycle, including disposal. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { final GlobalKey webViewKey = GlobalKey(); InAppWebViewController? webViewController; InAppWebViewSettings settings = InAppWebViewSettings(isInspectable: kDebugMode); PrintJobController? printJobController; @override void dispose() { // dispose any print job printJobController?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Print Job Controller'), actions: [ IconButton( onPressed: () async { // dispose any previous print job printJobController?.dispose(); final jobSettings = PrintJobSettings( handledByClient: true, jobName: "${await webViewController?.getTitle() ?? ''} - PDF Document example", colorMode: PrintJobColorMode.MONOCHROME, outputType: PrintJobOutputType.GRAYSCALE, orientation: PrintJobOrientation.LANDSCAPE, numberOfPages: 1); printJobController = await webViewController ?.printCurrentPage(settings: jobSettings); if (defaultTargetPlatform == TargetPlatform.iOS) { printJobController?.onComplete = (completed, error) async { if (completed) { print("Print Job Completed"); } else { print("Print Job Failed $error"); } printJobController?.dispose(); }; } final jobInfo = await printJobController?.getInfo(); print(jobInfo); }, icon: const Icon(Icons.print)) ], ), body: Column(children: [ Expanded( child: InAppWebView( key: webViewKey, initialUrlRequest: URLRequest(url: WebUri("https://github.com/flutter/")), initialSettings: settings, onWebViewCreated: (InAppWebViewController controller) { webViewController = controller; }, )), ])); } } ``` -------------------------------- ### Basic InAppWebView Setup and DevTools Protocol Integration Source: https://inappwebview.dev/docs/chrome-devtools-protocol This snippet demonstrates the basic setup of an InAppWebView in a Flutter application. It includes initializing the WebView, setting initial configurations, and preparing the Chrome DevTools Protocol by enabling the 'Page.enable' method and adding a listener for 'Page.loadEventFired' events. This is useful for debugging and interacting with the web content at a deeper level, especially on Windows platforms. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; WebViewEnvironment? webViewEnvironment; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.windows) { final availableVersion = await WebViewEnvironment.getAvailableVersion(); assert(availableVersion != null, 'Failed to find an installed WebView2 Runtime or non-stable Microsoft Edge installation.'); webViewEnvironment = await WebViewEnvironment.create( settings: WebViewEnvironmentSettings(userDataFolder: 'YOUR_CUSTOM_PATH')); } if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { final GlobalKey webViewKey = GlobalKey(); InAppWebViewController? webViewController; InAppWebViewSettings settings = InAppWebViewSettings( isInspectable: kDebugMode, mediaPlaybackRequiresUserGesture: false, allowsInlineMediaPlayback: true, iframeAllow: "camera; microphone", iframeAllowFullscreen: true); double progress = 0; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text("Official InAppWebView website")), body: SafeArea( child: Column(children: [ Expanded( child: Stack( children: [ InAppWebView( key: webViewKey, webViewEnvironment: webViewEnvironment, initialSettings: settings, onWebViewCreated: (controller) async { webViewController = controller; // Prepare DevTools Protocol if (!kIsWeb && defaultTargetPlatform == TargetPlatform.windows) { // Enables page domain notifications. await controller.callDevToolsProtocolMethod( methodName: 'Page.enable'); // Listen for a Page event await controller.addDevToolsProtocolEventListener( eventName: 'Page.loadEventFired', callback: (data) { print('Page.loadEventFired: $data'); }, ); } // Load your URL await controller.loadUrl( urlRequest: URLRequest( url: WebUri("https://inappwebview.dev/"))); }, onProgressChanged: (controller, progress) { setState(() { this.progress = progress / 100; }); }, ), progress < 1.0 ? LinearProgressIndicator(value: progress) : Container(), ], ), ), ButtonBar( alignment: MainAxisAlignment.center, children: [ ElevatedButton( child: const Icon(Icons.arrow_back), onPressed: () { webViewController?.goBack(); }, ), ElevatedButton( child: const Icon(Icons.arrow_forward), onPressed: () { webViewController?.goForward(); }, ), ElevatedButton( child: const Icon(Icons.refresh), onPressed: () { webViewController?.reload(); }, ), ], ), ]))); } } ``` -------------------------------- ### Flutter InAppWebView Setup and JavaScript Handler Registration Source: https://inappwebview.dev/docs/webview/javascript/communication This code demonstrates the complete setup for an InAppWebView, including initial data loading and the registration of two JavaScript handlers: 'handlerFoo' and 'handlerFooWithArgs'. 'handlerFoo' returns a JSON object, while 'handlerFooWithArgs' receives multiple arguments from JavaScript. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; WebViewEnvironment? webViewEnvironment; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.windows) { final availableVersion = await WebViewEnvironment.getAvailableVersion(); assert(availableVersion != null, 'Failed to find an installed WebView2 Runtime or non-stable Microsoft Edge installation.'); webViewEnvironment = await WebViewEnvironment.create( settings: WebViewEnvironmentSettings(userDataFolder: 'YOUR_CUSTOM_PATH')); } if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(new MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => new _MyAppState(); } class _MyAppState extends State { InAppWebViewSettings settings = InAppWebViewSettings( isInspectable: kDebugMode, mediaPlaybackRequiresUserGesture: false, allowsInlineMediaPlayback: true, iframeAllow: "camera; microphone", iframeAllowFullscreen: true); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text("JavaScript Handlers")), body: SafeArea( child: Column(children: [ Expanded( child: InAppWebView( webViewEnvironment: webViewEnvironment, initialData: InAppWebViewInitialData(data: """

JavaScript Handlers

"""), initialSettings: settings, onWebViewCreated: (controller) { controller.addJavaScriptHandler( handlerName: 'handlerFoo', callback: (JavaScriptHandlerFunctionData data) { // return data to the JavaScript side! return {'bar': 'bar_value', 'baz': 'baz_value'}; }); controller.addJavaScriptHandler( handlerName: 'handlerFooWithArgs', callback: (JavaScriptHandlerFunctionData data) { print(data); // it will print: // JavaScriptHandlerFunctionData{args: [1, true, [bar, 5], {foo: baz}, {bar: bar_value, baz: baz_value}], isMainFrame: true, origin: , requestUrl: about:blank} }); }, onConsoleMessage: (controller, consoleMessage) { print(consoleMessage); // it will print: {message: {"bar":"bar_value","baz":"baz_value"}, messageLevel: 1} }, ), ), ]))), ); } } ``` -------------------------------- ### Initialize and Run HeadlessInAppWebView Source: https://inappwebview.dev/docs/webview/headless-in-app-webview Sets up and runs a HeadlessInAppWebView with a specified initial URL and configures event handlers for creation, console messages, and load events. Use this to start a headless web view instance. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { HeadlessInAppWebView? headlessWebView; String url = ""; @override void initState() { super.initState(); headlessWebView = HeadlessInAppWebView( initialUrlRequest: URLRequest(url: WebUri("https://github.com/flutter")), initialSettings: InAppWebViewSettings(isInspectable: kDebugMode), onWebViewCreated: (controller) { const snackBar = SnackBar( content: Text('HeadlessInAppWebView created!'), duration: Duration(seconds: 1), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); }, onConsoleMessage: (controller, consoleMessage) { final snackBar = SnackBar( content: Text('Console Message: ${consoleMessage.message}'), duration: const Duration(seconds: 1), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); }, onLoadStart: (controller, url) async { final snackBar = SnackBar( content: Text('onLoadStart $url'), duration: const Duration(seconds: 1), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); setState(() { this.url = url?.toString() ?? ''; }); }, onLoadStop: (controller, url) async { final snackBar = SnackBar( content: Text('onLoadStop $url'), duration: const Duration(seconds: 1), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); setState(() { this.url = url?.toString() ?? ''; }); }, ); } @override void dispose() { super.dispose(); headlessWebView?.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "HeadlessInAppWebView Example", )), body: SafeArea( child: Column(children: [ Container( padding: const EdgeInsets.all(20.0), child: Text( "URL: ${(url.length > 50) ? \"${url.substring(0, 50)}\"..." : url}"), ), Center( child: ElevatedButton( onPressed: () async { await headlessWebView?.dispose(); await headlessWebView?.run(); }, child: const Text("Run HeadlessInAppWebView")), ), Center( child: ElevatedButton( onPressed: () async { if (headlessWebView?.isRunning() ?? false) { await headlessWebView?.webViewController ?.evaluateJavascript( source: "console.log('Here is the message!');"); } else { const snackBar = SnackBar( content: Text( 'HeadlessInAppWebView is not running. Click on "Run HeadlessInAppWebView"!'), duration: Duration(milliseconds: 1500), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } }, child: const Text("Send console.log message")), ), Center( child: ElevatedButton( onPressed: () { headlessWebView?.dispose(); setState(() { url = ''; }); }, child: const Text("Dispose HeadlessInAppWebView")), ) ]))); } } ``` -------------------------------- ### Basic Find Interaction Setup Source: https://inappwebview.dev/docs/webview/find-interaction-controller This snippet shows how to set up and toggle the find interaction functionality, including searching text and presenting the find navigator. ```dart await webViewController?.setSettings( settings: settings); setState(() { textFound = ''; }); await findInteractionController .setSearchText(searchController.text); if (isFindInteractionEnabled) { await findInteractionController .presentFindNavigator(); } ``` -------------------------------- ### JavaScript Initiated Communication Source: https://inappwebview.dev/docs/webview/javascript/communication Example of how a web page can set up a message handler and send an initial message to the app. ```javascript // Web page (in JavaScript) myObject.onmessage = function(event) { // prints "Got it!" when we receive the app's response. console.log(event.data); } myObject.postMessage("I'm ready!"); ``` -------------------------------- ### Basic Pull-To-Refresh Implementation Source: https://inappwebview.dev/docs/webview/pull-to-refresh-controller This example demonstrates how to set up and use the PullToRefreshController in a Flutter application. It includes initialization, configuration of settings, and handling the refresh event. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { final GlobalKey webViewKey = GlobalKey(); InAppWebViewController? webViewController; InAppWebViewSettings settings = InAppWebViewSettings(isInspectable: kDebugMode); PullToRefreshController? pullToRefreshController; PullToRefreshSettings pullToRefreshSettings = PullToRefreshSettings( color: Colors.blue, ); bool pullToRefreshEnabled = true; @override void initState() { super.initState(); pullToRefreshController = kIsWeb ? null : PullToRefreshController( settings: pullToRefreshSettings, onRefresh: () async { if (defaultTargetPlatform == TargetPlatform.android) { webViewController?.reload(); } else if (defaultTargetPlatform == TargetPlatform.iOS) { webViewController?.loadUrl( urlRequest: URLRequest(url: await webViewController?.getUrl())); } }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Pull-to-refresh Controller'), actions: [ TextButton( onPressed: () async { pullToRefreshEnabled = !pullToRefreshEnabled; await pullToRefreshController ?.setEnabled(pullToRefreshEnabled); setState(() {}); }, style: TextButton.styleFrom(foregroundColor: Colors.white), child: Text(pullToRefreshEnabled ? 'Disable' : 'Enable')) ], ), body: Column(children: [ Expanded( child: InAppWebView( key: webViewKey, initialUrlRequest: URLRequest(url: WebUri("https://github.com/flutter/")), initialSettings: settings, pullToRefreshController: pullToRefreshController, onWebViewCreated: (InAppWebViewController controller) { webViewController = controller; }, onLoadStop: (controller, url) { pullToRefreshController?.endRefreshing(); }, onReceivedError: (controller, request, error) { pullToRefreshController?.endRefreshing(); }, onProgressChanged: (controller, progress) { if (progress == 100) { pullToRefreshController?.endRefreshing(); } }, )), ])); } } ``` -------------------------------- ### Initialize InAppWebView with User Scripts Source: https://inappwebview.dev/docs/webview/javascript/user-scripts Use `initialUserScripts` to provide a list of `UserScript` objects when creating an `InAppWebView`. Scripts can be injected at document start or end. ```dart InAppWebView( initialUrlRequest: URLRequest(url: WebUri('https://flutter.dev')), initialUserScripts: UnmodifiableListView([ UserScript( source: "var foo = 49;", injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START), UserScript( source: "var bar = 2;", injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END), ]), onLoadStop: (controller, url) async { var result = await controller.evaluateJavascript(source: "foo + bar"); print(result); // 51 }, ) ``` -------------------------------- ### Pull-to-Refresh Controller Setup Source: https://inappwebview.dev/docs/webview/in-app-webview Initialize a PullToRefreshController for Android and iOS platforms to enable pull-to-refresh functionality within the WebView. The controller can be configured with custom settings and an onRefresh callback. ```dart pullToRefreshController = kIsWeb || ![TargetPlatform.iOS, TargetPlatform.android] .contains(defaultTargetPlatform) ? null : PullToRefreshController( settings: PullToRefreshSettings( color: Colors.blue, ), onRefresh: () async { if (defaultTargetPlatform == TargetPlatform.android) { webViewController?.reload(); } else if (defaultTargetPlatform == TargetPlatform.iOS) { webViewController?.loadUrl( urlRequest: ``` -------------------------------- ### Create a Web Message Channel Source: https://inappwebview.dev/docs/webview/javascript/communication Creates a new Web Message Channel. This should be called after the page has loaded, for example, when the WebView.onLoadStop event is fired. Ensure the feature is supported before calling. ```dart if (defaultTargetPlatform != TargetPlatform.android || await WebViewFeature.isFeatureSupported(WebViewFeature.CREATE_WEB_MESSAGE_CHANNEL)) { var webMessageChannel = await controller.createWebMessageChannel(); var port1 = webMessageChannel!.port1; var port2 = webMessageChannel.port2; } ``` -------------------------------- ### WebUri Example: Letter Case Preservation Source: https://inappwebview.dev/docs/web-uri Illustrates how WebUri preserves letter case for custom host values when `forceToStringRawValue` is false. Shows the difference between `rawValue`, `uriValue.toString()`, and `toString()` output. ```dart final uri = WebUri('scheme://customHostValue', forceToStringRawValue: false); print(uri.rawValue); // scheme://customHostValue print(uri.isValidUri); // true print(uri.uriValue.toString()); // scheme://customhostvalue print(uri.toString()); // scheme://customhostvalue uri.forceToStringRawValue = true; print(uri.toString()); // scheme://customHostValue ``` -------------------------------- ### Flutter InAppWebView Setup with Web Message Channel Source: https://inappwebview.dev/docs/webview/javascript/communication This code sets up the Flutter application, initializes the InAppWebView, and configures it to use Web Message Channels for communication. It includes the HTML structure for the web page with JavaScript to handle messages and a button to send data. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(true); } runApp(new MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => new _MyAppState(); } class _MyAppState extends State { InAppWebViewSettings settings = InAppWebViewSettings(); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text("Web Message Channels")), body: SafeArea( child: Column(children: [ Expanded( child: InAppWebView( initialData: InAppWebViewInitialData(data: """ WebMessageChannel Test
"""), initialSettings: settings, onConsoleMessage: (controller, consoleMessage) { print( "Message coming from the Dart side: ${consoleMessage.message}"); }, onLoadStop: (controller, url) async { if (defaultTargetPlatform != TargetPlatform.android || await WebViewFeature.isFeatureSupported( WebViewFeature.CREATE_WEB_MESSAGE_CHANNEL)) { // wait until the page is loaded, and then create the Web Message Channel var webMessageChannel = await controller.createWebMessageChannel(); var port1 = webMessageChannel!.port1; var port2 = webMessageChannel.port2; // set the web message callback for the port1 await port1.setWebMessageCallback((message) async { print( "Message coming from the JavaScript side: $message"); // when it receives a message from the JavaScript side, respond back with another message. await port1.postMessage( WebMessage(data: message! + " and back")); }); // transfer port2 to the webpage to initialize the communication await controller.postWebMessage( message: WebMessage(data: "capturePort", ports: [port2]), targetOrigin: WebUri("*")); } }, ), ), ]))), ); } } ``` -------------------------------- ### Basic Cookie Management in WebView Source: https://inappwebview.dev/docs/cookie-manager This snippet demonstrates how to get the CookieManager instance, set a cookie with an expiration date, retrieve all cookies for a URL, get a specific cookie by name, delete a specific cookie, and delete cookies by domain. ```dart // get the CookieManager instance CookieManager cookieManager = CookieManager.instance(); // set the expiration date for the cookie in milliseconds final expiresDate = DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch; final url = WebUri("https://flutter.dev/"); // set the cookie await cookieManager.setCookie( url: url, name: "myCookie", value: "myValue", expiresDate: expiresDate, isSecure: true, ); // get cookies List cookies = await cookieManager.getCookies(url: url); // get a cookie Cookie? cookie = await cookieManager.getCookie(url: url, name: "myCookie"); // delete a cookie await cookieManager.deleteCookie(url: url, name: "myCookie"); // delete cookies await cookieManager.deleteCookies(url: url, domain: ".flutter.dev"); ``` -------------------------------- ### Basic InAppWebView Initialization with WebUri Source: https://inappwebview.dev/docs/web-uri Demonstrates how to initialize an InAppWebView with a URL using the WebUri class. ```dart InAppWebView( initialUrlRequest: URLRequest(url: WebUri('https://flutter.dev')) ) ``` -------------------------------- ### Basic WebViewAssetLoader with Custom Domain Source: https://inappwebview.dev/docs/webview/webview-asset-loader Demonstrates how to initialize InAppWebView with WebViewAssetLoader to serve assets from a custom domain. Ensure to set up the domain and path handlers correctly. ```dart import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { final GlobalKey webViewKey = GlobalKey(); InAppWebViewSettings settings = InAppWebViewSettings( isInspectable: kDebugMode, // Setting this off for security. Off by default for SDK versions >= 16. allowFileAccessFromFileURLs: false, // Off by default, deprecated for SDK versions >= 30. allowUniversalAccessFromFileURLs: false, // Keeping these off is less critical but still a good idea, especially if your app is not // using file:// or content:// URLs. allowFileAccess: false, allowContentAccess: false, // Basic WebViewAssetLoader with custom domain webViewAssetLoader: WebViewAssetLoader( domain: "my.custom.domain.com", pathHandlers: [AssetsPathHandler(path: '/assets/')])); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('WebView Asset Loader'), ), body: Column(children: [ Expanded( child: InAppWebView( key: webViewKey, initialUrlRequest: URLRequest( url: WebUri( "https://my.custom.domain.com/assets/flutter_assets/assets/website/index.html")), initialSettings: settings, )), ])); } } ```