[
+ Container(
+ padding: EdgeInsets.all(20.0),
+ child: Text(
+ "CURRENT URL\n${(url.length > 50) ? url.substring(0, 50) + "..." : url}"),
+ ),
+ Container(
+ padding: EdgeInsets.all(10.0),
+ child: progress < 1.0
+ ? LinearProgressIndicator(value: progress)
+ : Container()),
+ Expanded(
+ child: Container(
+ margin: const EdgeInsets.all(10.0),
+ decoration:
+ BoxDecoration(border: Border.all(color: Colors.blueAccent)),
+ child: InAppWebView(
+ //initialUrl: "https://www.youtube.com/embed/M7lc1UVf-VE?playsinline=1",
+ //initialUrl: "https://github.com",
+ //initialUrl: "chrome://safe-browsing/match?type=malware",
+ //initialUrl: "http://192.168.1.20:8081/",
+ //initialUrl: "https://192.168.1.20:4433/",
+ initialFile: "assets/index.html",
+ initialHeaders: {},
+ initialOptions: InAppWebViewWidgetOptions(
+ inAppWebViewOptions: InAppWebViewOptions(
+ //disableVerticalScroll: false,
+ //disableHorizontalScroll: false,
+ debuggingEnabled: true,
+ clearCache: true,
+ useShouldOverrideUrlLoading: true,
+ useOnTargetBlank: true,
+ useOnLoadResource: true,
+ useOnDownloadStart: true,
+ useShouldInterceptAjaxRequest: true,
+ useShouldInterceptFetchRequest: true,
+ //preferredContentMode: InAppWebViewUserPreferredContentMode.DESKTOP,
+ resourceCustomSchemes: [
+ "my-special-custom-scheme"
+ ],
+ contentBlockers: [
+ ContentBlocker(
+ trigger: ContentBlockerTrigger(
+ urlFilter: ".*",
+ resourceType: [
+ ContentBlockerTriggerResourceType.IMAGE,
+ ContentBlockerTriggerResourceType.STYLE_SHEET
+ ],
+ ifTopUrl: [
+ "https://getbootstrap.com/"
+ ]),
+ action: ContentBlockerAction(
+ type: ContentBlockerActionType.BLOCK))
+ ]),
+ androidInAppWebViewOptions: AndroidInAppWebViewOptions(
+ databaseEnabled: true,
+ domStorageEnabled: true,
+ geolocationEnabled: true,
+ //safeBrowsingEnabled: true,
+ //blockNetworkImage: true,
+ ),
+ ),
+ onWebViewCreated: (InAppWebViewController controller) {
+ webView = controller;
+
+ if (Platform.isAndroid) webView.startSafeBrowsing();
+
+ webView.addJavaScriptHandler(
+ handlerName: 'handlerFoo',
+ callback: (args) {
+ return new Foo(bar: 'bar_value', baz: 'baz_value');
+ });
+
+ webView.addJavaScriptHandler(
+ handlerName: 'handlerFooWithArgs',
+ callback: (args) {
+ print(args);
+ return [
+ args[0] + 5,
+ !args[1],
+ args[2][0],
+ args[3]['foo']
+ ];
+ });
+ },
+ onLoadStart: (InAppWebViewController controller, String url) {
+ print("started $url");
+ setState(() {
+ this.url = url;
+ });
+ },
+ onLoadStop:
+ (InAppWebViewController controller, String url) async {
+ print("stopped $url");
+ if (Platform.isAndroid) {
+ controller.clearSslPreferences();
+ controller.clearClientCertPreferences();
+ }
+ //controller.findAllAsync("flutter");
+ print(await controller.getFavicons());
+ },
+ onLoadError: (InAppWebViewController controller, String url,
+ int code, String message) async {
+ print("error $url: $code, $message");
+
+ var tRexHtml = await controller.getTRexRunnerHtml();
+ var tRexCss = await controller.getTRexRunnerCss();
+
+ controller.loadData(data: """
+
+
+
+
+
+
+
+ $tRexHtml
+
+ URL $url failed to load.
+
+
+ Error: $code, $message
+
+
+
+ """);
+ },
+ onProgressChanged:
+ (InAppWebViewController controller, int progress) {
+ setState(() {
+ this.progress = progress / 100;
+ });
+ },
+ shouldOverrideUrlLoading:
+ (InAppWebViewController controller, String url) {
+ print("override $url");
+ controller.loadUrl(url: url);
+ },
+ onLoadResource: (InAppWebViewController controller,
+ LoadedResource response) {
+ print("Resource type: '" +
+ response.initiatorType +
+ "' started at: " +
+ response.startTime.toString() +
+ "ms ---> duration: " +
+ response.duration.toString() +
+ "ms " +
+ response.url);
+ },
+ onConsoleMessage: (InAppWebViewController controller,
+ ConsoleMessage consoleMessage) {
+ print("""
+ console output:
+ message: ${consoleMessage.message}
+ messageLevel: ${consoleMessage.messageLevel.toString()}
+ """);
+ },
+ onDownloadStart:
+ (InAppWebViewController controller, String url) async {
+ // final taskId = await FlutterDownloader.enqueue(
+ // url: url,
+ // savedDir: await _findLocalPath(),
+ // showNotification: true, // show download progress in status bar (for Android)
+ // openFileFromNotification: true, // click on notification to open downloaded file (for Android)
+ // );
+ },
+ onLoadResourceCustomScheme: (InAppWebViewController controller,
+ String scheme, String url) async {
+ if (scheme == "my-special-custom-scheme") {
+ var bytes = await rootBundle.load("assets/" +
+ url.replaceFirst("my-special-custom-scheme://", "", 0));
+ var response = new CustomSchemeResponse(
+ data: bytes.buffer.asUint8List(),
+ contentType: "image/svg+xml",
+ contentEnconding: "utf-8");
+ return response;
+ }
+ return null;
+ },
+ onTargetBlank: (InAppWebViewController controller, String url) {
+ print("target _blank: " + url);
+ controller.loadUrl(url: url);
+ },
+ onGeolocationPermissionsShowPrompt:
+ (InAppWebViewController controller, String origin) async {
+ GeolocationPermissionShowPromptResponse response;
+
+ await showDialog(
+ context: context,
+ builder: (BuildContext context) {
+ return AlertDialog(
+ title: Text("Permission Geolocation API"),
+ content: Text("Can we use Geolocation API?"),
+ actions: [
+ FlatButton(
+ child: Text("Close"),
+ onPressed: () {
+ response =
+ new GeolocationPermissionShowPromptResponse(
+ origin: origin,
+ allow: false,
+ retain: false);
+ Navigator.of(context).pop();
+ },
+ ),
+ FlatButton(
+ child: Text("Accept"),
+ onPressed: () {
+ response =
+ new GeolocationPermissionShowPromptResponse(
+ origin: origin,
+ allow: true,
+ retain: true);
+ Navigator.of(context).pop();
+ },
+ ),
+ ],
+ );
+ },
+ );
+
+ return response;
+ },
+ onJsAlert:
+ (InAppWebViewController controller, String message) async {
+ JsAlertResponseAction action =
+ await createAlertDialog(context, message);
+ return new JsAlertResponse(
+ handledByClient: true, action: action);
+ },
+ onJsConfirm:
+ (InAppWebViewController controller, String message) async {
+ JsConfirmResponseAction action =
+ await createConfirmDialog(context, message);
+ return new JsConfirmResponse(
+ handledByClient: true, action: action);
+ },
+ onJsPrompt: (InAppWebViewController controller, String message,
+ String defaultValue) async {
+ _textFieldController.text = defaultValue;
+ JsPromptResponseAction action =
+ await createPromptDialog(context, message);
+ return new JsPromptResponse(
+ handledByClient: true,
+ action: action,
+ value: _textFieldController.text);
+ },
+ onSafeBrowsingHit: (InAppWebViewController controller,
+ String url, SafeBrowsingThreat threatType) async {
+ SafeBrowsingResponseAction action =
+ SafeBrowsingResponseAction.BACK_TO_SAFETY;
+ return new SafeBrowsingResponse(report: true, action: action);
+ },
+ onReceivedHttpAuthRequest: (InAppWebViewController controller,
+ HttpAuthChallenge challenge) async {
+ print(
+ "HTTP AUTH REQUEST: ${challenge.protectionSpace.host}, realm: ${challenge.protectionSpace.realm}, previous failure count: ${challenge.previousFailureCount.toString()}");
+
+ return new HttpAuthResponse(
+ username: "USERNAME",
+ password: "PASSWORD",
+ action: HttpAuthResponseAction
+ .USE_SAVED_HTTP_AUTH_CREDENTIALS,
+ permanentPersistence: true);
+ },
+ onReceivedServerTrustAuthRequest:
+ (InAppWebViewController controller,
+ ServerTrustChallenge challenge) async {
+ print(
+ "SERVER TRUST AUTH REQUEST: ${challenge.protectionSpace.host}, SSL ERROR CODE: ${challenge.error.toString()}, MESSAGE: ${challenge.message}");
+
+ return new ServerTrustAuthResponse(
+ action: ServerTrustAuthResponseAction.PROCEED);
+ },
+ onReceivedClientCertRequest: (InAppWebViewController controller,
+ ClientCertChallenge challenge) async {
+ print(
+ "CLIENT CERT REQUEST: ${challenge.protectionSpace.host}");
+
+ return new ClientCertResponse(
+ certificatePath: "assets/certificate.pfx",
+ certificatePassword: "",
+ androidKeyStoreType: "PKCS12",
+ action: ClientCertResponseAction.PROCEED);
+ },
+ onFindResultReceived: (InAppWebViewController controller,
+ int activeMatchOrdinal,
+ int numberOfMatches,
+ bool isDoneCounting) async {
+ print(
+ "Current highlighted: $activeMatchOrdinal, Number of matches found: $numberOfMatches, find operation completed: $isDoneCounting");
+ },
+ shouldInterceptAjaxRequest: (InAppWebViewController controller,
+ AjaxRequest ajaxRequest) async {
+ print(
+ "AJAX REQUEST: ${ajaxRequest.method} - ${ajaxRequest.url}, DATA: ${ajaxRequest.data}, headers: ${ajaxRequest.headers}");
+ if (ajaxRequest.url ==
+ "http://192.168.1.20:8082/test-ajax-post") {
+ ajaxRequest.responseType = 'json';
+ ajaxRequest.data = "firstname=Lorenzo&lastname=Pichilli";
+ }
+ // ajaxRequest.method = "GET";
+ // ajaxRequest.url = "http://192.168.1.20:8082/test-download-file";
+ // ajaxRequest.headers = {
+ // "Custom-Header": "Custom-Value"
+ // };
+ // return ajaxRequest;
+ return ajaxRequest;
+ },
+ onAjaxReadyStateChange: (InAppWebViewController controller,
+ AjaxRequest ajaxRequest) async {
+ print(
+ "AJAX READY STATE CHANGE: ${ajaxRequest.method} - ${ajaxRequest.url}, ${ajaxRequest.status}, ${ajaxRequest.readyState}, ${ajaxRequest.responseType}, ${ajaxRequest.responseText}, ${ajaxRequest.response}, ${ajaxRequest.responseHeaders}");
+ return AjaxRequestAction.PROCEED;
+ },
+ onAjaxProgress: (InAppWebViewController controller,
+ AjaxRequest ajaxRequest) async {
+ print(
+ "AJAX EVENT: ${ajaxRequest.method} - ${ajaxRequest.url}, ${ajaxRequest.event.type}, LOADED: ${ajaxRequest.event.loaded}, ${ajaxRequest.responseHeaders}");
+ return AjaxRequestAction.PROCEED;
+ },
+ shouldInterceptFetchRequest: (InAppWebViewController controller,
+ FetchRequest fetchRequest) async {
+ print(
+ "FETCH REQUEST: ${fetchRequest.method} - ${fetchRequest.url}, headers: ${fetchRequest.headers}");
+ fetchRequest.action = FetchRequestAction.ABORT;
+ print(fetchRequest.body);
+ return fetchRequest;
+ },
+ onNavigationStateChange:
+ (InAppWebViewController controller, String url) async {
+ print("NAVIGATION STATE CHANGE: $url");
+ setState(() {
+ this.url = url;
+ });
+ },
+ ),
+ ),
+ ),
+ ButtonBar(
+ alignment: MainAxisAlignment.center,
+ children: [
+ RaisedButton(
+ child: Icon(Icons.arrow_back),
+ onPressed: () {
+ if (webView != null) {
+ webView.goBack();
+ }
+ },
+ ),
+ RaisedButton(
+ child: Icon(Icons.arrow_forward),
+ onPressed: () {
+ if (webView != null) {
+ webView.goForward();
+ }
+ },
+ ),
+ RaisedButton(
+ child: Icon(Icons.refresh),
+ onPressed: () {
+ if (webView != null) {
+ webView.reload();
+ }
+ },
+ ),
+ ],
+ ),
+ ])));
+ }
+
+ Future createAlertDialog(
+ BuildContext context, String message) async {
+ JsAlertResponseAction action;
+
+ await showDialog(
+ context: context,
+ builder: (BuildContext context) {
+ return AlertDialog(
+ content: Text(message),
+ actions: [
+ FlatButton(
+ child: Text("Ok"),
+ onPressed: () {
+ action = JsAlertResponseAction.CONFIRM;
+ Navigator.of(context).pop();
+ },
+ ),
+ ],
+ );
+ },
+ );
+
+ return action;
+ }
+
+ Future createConfirmDialog(
+ BuildContext context, String message) async {
+ JsConfirmResponseAction action;
+
+ await showDialog(
+ context: context,
+ builder: (BuildContext context) {
+ return AlertDialog(
+ content: Text(message),
+ actions: [
+ FlatButton(
+ child: Text("Cancel"),
+ onPressed: () {
+ action = JsConfirmResponseAction.CANCEL;
+ Navigator.of(context).pop();
+ },
+ ),
+ FlatButton(
+ child: Text("Ok"),
+ onPressed: () {
+ action = JsConfirmResponseAction.CONFIRM;
+ Navigator.of(context).pop();
+ },
+ ),
+ ],
+ );
+ },
+ );
+
+ return action;
+ }
+
+ Future createPromptDialog(
+ BuildContext context, String message) async {
+ JsPromptResponseAction action;
+
+ await showDialog(
+ context: context,
+ builder: (BuildContext context) {
+ return AlertDialog(
+ title: Text(message),
+ content: TextField(
+ controller: _textFieldController,
+ ),
+ actions: [
+ FlatButton(
+ child: Text("Cancel"),
+ onPressed: () {
+ action = JsPromptResponseAction.CANCEL;
+ Navigator.of(context).pop();
+ },
+ ),
+ FlatButton(
+ child: Text("Ok"),
+ onPressed: () {
+ action = JsPromptResponseAction.CONFIRM;
+ Navigator.of(context).pop();
+ },
+ ),
+ ],
+ );
+ },
+ );
+
+ return action;
+ }
+
+ Future _findLocalPath() async {
+ final directory = Platform.isAndroid
+ ? await getExternalStorageDirectory()
+ : await getApplicationDocumentsDirectory();
+ return directory.path;
+ }
+}
diff --git a/example/lib/inline_example.screen.dart b/example/lib/inline_example.screen.dart
deleted file mode 100755
index 0035030d..00000000
--- a/example/lib/inline_example.screen.dart
+++ /dev/null
@@ -1,453 +0,0 @@
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-import 'dart:typed_data';
-
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
-import 'package:flutter_downloader/flutter_downloader.dart';
-import 'package:path_provider/path_provider.dart';
-import 'package:flutter/services.dart' show rootBundle;
-
-class InlineExampleScreen extends StatefulWidget {
- @override
- _InlineExampleScreenState createState() => new _InlineExampleScreenState();
-}
-
-class Foo {
- String bar;
- String baz;
-
- Foo({this.bar, this.baz});
-
- Map toJson() {
- return {
- 'bar': this.bar,
- 'baz': this.baz
- };
- }
-}
-
-class _InlineExampleScreenState extends State {
- InAppWebViewController webView;
- String url = "";
- double progress = 0;
-
- TextEditingController _textFieldController = TextEditingController();
-
- @override
- void initState() {
- super.initState();
- }
-
- @override
- void dispose() {
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
-// HttpAuthCredentialDatabase.instance().clearAllAuthCredentials();
-//
-// HttpAuthCredentialDatabase.instance().getHttpAuthCredentials(ProtectionSpace(host: "192.168.1.20", protocol: "http", realm: "Node", port: 8081)).then((credentials) {
-// for (var credential in credentials )
-// print("\n\nCREDENTIAL: ${credential.username} ${credential.password}\n\n");
-// });
-// HttpAuthCredentialDatabase.instance().getAllAuthCredentials().then((result) {
-// for (var r in result) {
-// ProtectionSpace protectionSpace = r["protectionSpace"];
-// print("\n\nProtectionSpace: ${protectionSpace.protocol} ${protectionSpace.host}:");
-// List credentials = r["credentials"];
-// for (var credential in credentials)
-// print("\tCREDENTIAL: ${credential.username} ${credential.password}");
-// }
-// });
-// HttpAuthCredentialDatabase.instance().setHttpAuthCredential(ProtectionSpace(host: "192.168.1.20", protocol: "http", realm: "Node", port: 8081), HttpAuthCredential(username: "user 1", password: "password 1"));
-// HttpAuthCredentialDatabase.instance().setHttpAuthCredential(ProtectionSpace(host: "192.168.1.20", protocol: "http", realm: "Node", port: 8081), HttpAuthCredential(username: "user 2", password: "password 2"));
-
- return Container(
- child: Column(children: [
- Container(
- padding: EdgeInsets.all(20.0),
- child: Text(
- "CURRENT URL\n${(url.length > 50) ? url.substring(0, 50) + "..." : url}"),
- ),
- Container(
- padding: EdgeInsets.all(10.0),
- child: progress < 1.0 ? LinearProgressIndicator(value: progress) : Container()
- ),
- Expanded(
- child: Container(
- margin: const EdgeInsets.all(10.0),
- decoration:
- BoxDecoration(border: Border.all(color: Colors.blueAccent)),
- child: InAppWebView(
- //initialUrl: "https://www.youtube.com/embed/M7lc1UVf-VE?playsinline=1",
- //initialUrl: "https://github.com",
- //initialUrl: "chrome://safe-browsing/match?type=malware",
- //initialUrl: "http://192.168.1.20:8081/",
- //initialUrl: "https://192.168.1.20:4433/",
- initialFile: "assets/index.html",
- initialHeaders: {},
- initialOptions: InAppWebViewWidgetOptions(
- inAppWebViewOptions: InAppWebViewOptions(
- debuggingEnabled: true,
- clearCache: true,
- useShouldOverrideUrlLoading: true,
- useOnTargetBlank: true,
- useOnLoadResource: true,
- useOnDownloadStart: true,
- useShouldInterceptAjaxRequest: true,
- useShouldInterceptFetchRequest: true,
- //preferredContentMode: InAppWebViewUserPreferredContentMode.DESKTOP,
- resourceCustomSchemes: ["my-special-custom-scheme"],
- contentBlockers: [
- ContentBlocker(
- trigger: ContentBlockerTrigger(
- urlFilter: ".*",
- resourceType: [ContentBlockerTriggerResourceType.IMAGE, ContentBlockerTriggerResourceType.STYLE_SHEET],
- ifTopUrl: ["https://getbootstrap.com/"]),
- action: ContentBlockerAction(type: ContentBlockerActionType.BLOCK)
- )
- ]
- ),
- androidInAppWebViewOptions: AndroidInAppWebViewOptions(
- databaseEnabled: true,
- domStorageEnabled: true,
- geolocationEnabled: true,
- //safeBrowsingEnabled: true,
- //blockNetworkImage: true,
- ),
- ),
- onWebViewCreated: (InAppWebViewController controller) {
- webView = controller;
-
- if (Platform.isAndroid)
- webView.startSafeBrowsing();
-
- webView.addJavaScriptHandler(handlerName:'handlerFoo', callback: (args) {
- return new Foo(bar: 'bar_value', baz: 'baz_value');
- });
-
- webView.addJavaScriptHandler(handlerName: 'handlerFooWithArgs', callback: (args) {
- print(args);
- return [args[0] + 5, !args[1], args[2][0], args[3]['foo']];
- });
- },
- onLoadStart: (InAppWebViewController controller, String url) {
- print("started $url");
- setState(() {
- this.url = url;
- });
- },
- onLoadStop: (InAppWebViewController controller, String url) async {
- print("stopped $url");
- if (Platform.isAndroid) {
- controller.clearSslPreferences();
- controller.clearClientCertPreferences();
- }
- //controller.findAllAsync("flutter");
- print(await controller.getFavicons());
- },
- onLoadError: (InAppWebViewController controller, String url, int code, String message) async {
- print("error $url: $code, $message");
-
- var tRexHtml = await controller.getTRexRunnerHtml();
- var tRexCss = await controller.getTRexRunnerCss();
-
- controller.loadData(data: """
-
-
-
-
-
-
-
- $tRexHtml
-
- URL $url failed to load.
-
-
- Error: $code, $message
-
-
-
- """);
- },
- onProgressChanged:
- (InAppWebViewController controller, int progress) {
- setState(() {
- this.progress = progress / 100;
- });
- },
- shouldOverrideUrlLoading: (InAppWebViewController controller, String url) {
- print("override $url");
- controller.loadUrl(url: url);
- },
- onLoadResource: (InAppWebViewController controller, LoadedResource response) {
- print("Resource type: '"+response.initiatorType + "' started at: " +
- response.startTime.toString() +
- "ms ---> duration: " +
- response.duration.toString() +
- "ms " +
- response.url);
- },
- onConsoleMessage: (InAppWebViewController controller, ConsoleMessage consoleMessage) {
- print("""
- console output:
- message: ${consoleMessage.message}
- messageLevel: ${consoleMessage.messageLevel.toString()}
- """);
- },
- onDownloadStart: (InAppWebViewController controller, String url) async {
-// final taskId = await FlutterDownloader.enqueue(
-// url: url,
-// savedDir: await _findLocalPath(),
-// showNotification: true, // show download progress in status bar (for Android)
-// openFileFromNotification: true, // click on notification to open downloaded file (for Android)
-// );
- },
- onLoadResourceCustomScheme: (InAppWebViewController controller, String scheme, String url) async {
- if (scheme == "my-special-custom-scheme") {
- var bytes = await rootBundle.load("assets/" + url.replaceFirst("my-special-custom-scheme://", "", 0));
- var response = new CustomSchemeResponse(data: bytes.buffer.asUint8List(), contentType: "image/svg+xml", contentEnconding: "utf-8");
- return response;
- }
- return null;
- },
- onTargetBlank: (InAppWebViewController controller, String url) {
- print("target _blank: " + url);
- controller.loadUrl(url: url);
- },
- onGeolocationPermissionsShowPrompt: (InAppWebViewController controller, String origin) async {
- GeolocationPermissionShowPromptResponse response;
-
- await showDialog(
- context: context,
- builder: (BuildContext context) {
- return AlertDialog(
- title: Text("Permission Geolocation API"),
- content: Text("Can we use Geolocation API?"),
- actions: [
- FlatButton(
- child: Text("Close"),
- onPressed: () {
- response = new GeolocationPermissionShowPromptResponse(origin: origin, allow: false, retain: false);
- Navigator.of(context).pop();
- },
- ),
- FlatButton(
- child: Text("Accept"),
- onPressed: () {
- response = new GeolocationPermissionShowPromptResponse(origin: origin, allow: true, retain: true);
- Navigator.of(context).pop();
- },
- ),
- ],
- );
- },
- );
-
- return response;
- },
- onJsAlert: (InAppWebViewController controller, String message) async {
- JsAlertResponseAction action = await createAlertDialog(context, message);
- return new JsAlertResponse(handledByClient: true, action: action);
- },
- onJsConfirm: (InAppWebViewController controller, String message) async {
- JsConfirmResponseAction action = await createConfirmDialog(context, message);
- return new JsConfirmResponse(handledByClient: true, action: action);
- },
- onJsPrompt: (InAppWebViewController controller, String message, String defaultValue) async {
- _textFieldController.text = defaultValue;
- JsPromptResponseAction action = await createPromptDialog(context, message);
- return new JsPromptResponse(handledByClient: true, action: action, value: _textFieldController.text);
- },
- onSafeBrowsingHit: (InAppWebViewController controller, String url, SafeBrowsingThreat threatType) async {
- SafeBrowsingResponseAction action = SafeBrowsingResponseAction.BACK_TO_SAFETY;
- return new SafeBrowsingResponse(report: true, action: action);
- },
- onReceivedHttpAuthRequest: (InAppWebViewController controller, HttpAuthChallenge challenge) async {
- print("HTTP AUTH REQUEST: ${challenge.protectionSpace.host}, realm: ${challenge.protectionSpace.realm}, previous failure count: ${challenge.previousFailureCount.toString()}");
-
- return new HttpAuthResponse(username: "USERNAME", password: "PASSWORD", action: HttpAuthResponseAction.USE_SAVED_HTTP_AUTH_CREDENTIALS, permanentPersistence: true);
- },
- onReceivedServerTrustAuthRequest: (InAppWebViewController controller, ServerTrustChallenge challenge) async {
- print("SERVER TRUST AUTH REQUEST: ${challenge.protectionSpace.host}, SSL ERROR CODE: ${challenge.error.toString()}, MESSAGE: ${challenge.message}");
-
- return new ServerTrustAuthResponse(action: ServerTrustAuthResponseAction.PROCEED);
- },
- onReceivedClientCertRequest: (InAppWebViewController controller, ClientCertChallenge challenge) async {
- print("CLIENT CERT REQUEST: ${challenge.protectionSpace.host}");
-
- return new ClientCertResponse(certificatePath: "assets/certificate.pfx", certificatePassword: "", androidKeyStoreType: "PKCS12", action: ClientCertResponseAction.PROCEED);
- },
- onFindResultReceived: (InAppWebViewController controller, int activeMatchOrdinal, int numberOfMatches, bool isDoneCounting) async {
- print("Current highlighted: $activeMatchOrdinal, Number of matches found: $numberOfMatches, find operation completed: $isDoneCounting");
- },
- shouldInterceptAjaxRequest: (InAppWebViewController controller, AjaxRequest ajaxRequest) async {
- print("AJAX REQUEST: ${ajaxRequest.method} - ${ajaxRequest.url}, DATA: ${ajaxRequest.data}, headers: ${ajaxRequest.headers}");
- if (ajaxRequest.url == "http://192.168.1.20:8082/test-ajax-post") {
- ajaxRequest.responseType = 'json';
- ajaxRequest.data = "firstname=Lorenzo&lastname=Pichilli";
- }
-// ajaxRequest.method = "GET";
-// ajaxRequest.url = "http://192.168.1.20:8082/test-download-file";
-// ajaxRequest.headers = {
-// "Custom-Header": "Custom-Value"
-// };
-// return ajaxRequest;
- return ajaxRequest;
- },
- onAjaxReadyStateChange: (InAppWebViewController controller, AjaxRequest ajaxRequest) async {
- print("AJAX READY STATE CHANGE: ${ajaxRequest.method} - ${ajaxRequest.url}, ${ajaxRequest.status}, ${ajaxRequest.readyState}, ${ajaxRequest.responseType}, ${ajaxRequest.responseText}, ${ajaxRequest.response}, ${ajaxRequest.responseHeaders}");
- return AjaxRequestAction.PROCEED;
- },
- onAjaxProgress: (InAppWebViewController controller, AjaxRequest ajaxRequest) async {
- print("AJAX EVENT: ${ajaxRequest.method} - ${ajaxRequest.url}, ${ajaxRequest.event.type}, LOADED: ${ajaxRequest.event.loaded}, ${ajaxRequest.responseHeaders}");
- return AjaxRequestAction.PROCEED;
- },
- shouldInterceptFetchRequest: (InAppWebViewController controller, FetchRequest fetchRequest) async {
- print("FETCH REQUEST: ${fetchRequest.method} - ${fetchRequest.url}, headers: ${fetchRequest.headers}");
- fetchRequest.action = FetchRequestAction.ABORT;
- print(fetchRequest.body);
- return fetchRequest;
- },
- onNavigationStateChange: (InAppWebViewController controller, String url) async {
- print("NAVIGATION STATE CHANGE: $url");
- setState(() {
- this.url = url;
- });
- },
- ),
- ),
- ),
- ButtonBar(
- alignment: MainAxisAlignment.center,
- children: [
- RaisedButton(
- child: Icon(Icons.arrow_back),
- onPressed: () {
- if (webView != null) {
- webView.goBack();
- }
- },
- ),
- RaisedButton(
- child: Icon(Icons.arrow_forward),
- onPressed: () {
- if (webView != null) {
- webView.goForward();
- }
- },
- ),
- RaisedButton(
- child: Icon(Icons.refresh),
- onPressed: () {
- if (webView != null) {
- webView.reload();
- }
- },
- ),
- ],
- ),
- ]));
- }
-
- Future createAlertDialog(BuildContext context, String message) async {
- JsAlertResponseAction action;
-
- await showDialog(
- context: context,
- builder: (BuildContext context) {
- return AlertDialog(
- content: Text(message),
- actions: [
- FlatButton(
- child: Text("Ok"),
- onPressed: () {
- action = JsAlertResponseAction.CONFIRM;
- Navigator.of(context).pop();
- },
- ),
- ],
- );
- },
- );
-
- return action;
- }
-
- Future createConfirmDialog(BuildContext context, String message) async {
- JsConfirmResponseAction action;
-
- await showDialog(
- context: context,
- builder: (BuildContext context) {
- return AlertDialog(
- content: Text(message),
- actions: [
- FlatButton(
- child: Text("Cancel"),
- onPressed: () {
- action = JsConfirmResponseAction.CANCEL;
- Navigator.of(context).pop();
- },
- ),
- FlatButton(
- child: Text("Ok"),
- onPressed: () {
- action = JsConfirmResponseAction.CONFIRM;
- Navigator.of(context).pop();
- },
- ),
- ],
- );
- },
- );
-
- return action;
- }
-
- Future createPromptDialog(BuildContext context, String message) async {
- JsPromptResponseAction action;
-
- await showDialog(
- context: context,
- builder: (BuildContext context) {
- return AlertDialog(
- title: Text(message),
- content: TextField(
- controller: _textFieldController,
- ),
- actions: [
- FlatButton(
- child: Text("Cancel"),
- onPressed: () {
- action = JsPromptResponseAction.CANCEL;
- Navigator.of(context).pop();
- },
- ),
- FlatButton(
- child: Text("Ok"),
- onPressed: () {
- action = JsPromptResponseAction.CONFIRM;
- Navigator.of(context).pop();
- },
- ),
- ],
- );
- },
- );
-
- return action;
- }
-
- Future _findLocalPath() async {
- final directory = Platform.isAndroid
- ? await getExternalStorageDirectory()
- : await getApplicationDocumentsDirectory();
- return directory.path;
- }
-}
\ No newline at end of file
diff --git a/example/lib/main.dart b/example/lib/main.dart
index fd1ef227..0684a50b 100644
--- a/example/lib/main.dart
+++ b/example/lib/main.dart
@@ -3,9 +3,9 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
-import 'package:flutter_inappbrowser_example/chrome_safari_example.screen.dart';
-import 'package:flutter_inappbrowser_example/inline_example.screen.dart';
-import 'package:flutter_inappbrowser_example/webview_example.screen.dart';
+import 'package:flutter_inappbrowser_example/chrome_safari_browser_example.screen.dart';
+import 'package:flutter_inappbrowser_example/in_app_webiew_example.screen.dart';
+import 'package:flutter_inappbrowser_example/in_app_browser_example.screen.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:permission_handler/permission_handler.dart';
@@ -39,32 +39,12 @@ class _MyAppState extends State {
@override
Widget build(BuildContext context) {
return MaterialApp(
- home: DefaultTabController(
- length: 3,
- child: Scaffold(
- appBar: AppBar(
- title: Text('Tabs Demo'),
- ),
- body: TabBarView(
- children: [
- WebviewExampleScreen(),
- ChromeSafariExampleScreen(),
- InlineExampleScreen(),
- ],
- ),
- bottomNavigationBar: Container(
- color: Theme.of(context).primaryColor,
- child: TabBar(
- indicatorColor: Colors.white,
- tabs: [
- Tab(text: "Webview"),
- Tab(text: "Chrome/Safari"),
- Tab(
- text: "Inline",
- ),
- ],
- ),
- ))),
+ initialRoute: '/',
+ routes: {
+ '/': (context) => InAppWebViewExampleScreen(),
+ '/InAppBrowser': (context) => InAppBrowserExampleScreen(),
+ '/ChromeSafariBrowser': (context) => ChromeSafariBrowserExampleScreen(),
+ }
);
}
}
diff --git a/example/lib/webview_example.screen.dart b/example/lib/webview_example.screen.dart
deleted file mode 100644
index 73912fda..00000000
--- a/example/lib/webview_example.screen.dart
+++ /dev/null
@@ -1,137 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
-
-class MyInAppBrowser extends InAppBrowser {
-
- @override
- Future onBrowserCreated() async {
- print("\n\nBrowser Ready!\n\n");
- }
-
- @override
- Future onLoadStart(String url) async {
- print("\n\nStarted $url\n\n");
- }
-
- @override
- Future onLoadStop(String url) async {
- print("\n\nStopped $url\n\n");
- }
-
- @override
- Future onScrollChanged(int x, int y) async {
- print("Scrolled: x:$x y:$y");
- }
-
- @override
- void onLoadError(String url, int code, String message) {
- print("Can't load $url.. Error: $message");
- }
-
- @override
- void onProgressChanged(int progress) {
- print("Progress: $progress");
- }
-
- @override
- void onExit() {
- print("\n\nBrowser closed!\n\n");
- }
-
- @override
- void shouldOverrideUrlLoading(String url) {
- print("\n\n override $url\n\n");
- this.webViewController.loadUrl(url: url);
- }
-
- @override
- void onLoadResource(LoadedResource response) {
- print("Started at: " +
- response.startTime.toString() +
- "ms ---> duration: " +
- response.duration.toString() +
- "ms " +
- response.url);
- }
-
- @override
- void onConsoleMessage(ConsoleMessage consoleMessage) {
- print("""
- console output:
- message: ${consoleMessage.message}
- messageLevel: ${consoleMessage.messageLevel.toValue()}
- """);
- }
-
- @override
- void onDownloadStart(String url) {
- print("Download of " + url);
- }
-
- @override
- Future onLoadResourceCustomScheme(String scheme, String url) async {
- print("custom scheme: " + scheme);
- return null;
- }
-
- @override
- Future onGeolocationPermissionsShowPrompt(String origin) async {
- print("request Geolocation permission API");
- return null;
- }
-
- @override
- Future onJsAlert(String message) async {
- return new JsAlertResponse(handledByClient: false, message: "coma iam");
- }
-
- @override
- Future onJsConfirm(String message) {
- return null;
- }
-
- @override
- Future onJsPrompt(String message, String defaultValue) {
- return null;
- }
-}
-
-class WebviewExampleScreen extends StatefulWidget {
- final MyInAppBrowser browser = new MyInAppBrowser();
- static BuildContext context;
-
- @override
- _WebviewExampleScreenState createState() => new _WebviewExampleScreenState();
-}
-
-class _WebviewExampleScreenState extends State {
- @override
- void initState() {
- super.initState();
- }
-
- @override
- Widget build(BuildContext context) {
- WebviewExampleScreen.context = context;
- return new Center(
- child: new RaisedButton(
- onPressed: () {
- widget.browser.openFile(
- assetFilePath: "assets/index.html",
- //url: "https://www.google.com/",
- options: InAppBrowserClassOptions(
- inAppWebViewWidgetOptions: InAppWebViewWidgetOptions(
- inAppWebViewOptions: InAppWebViewOptions(
- useShouldOverrideUrlLoading: true,
- useOnLoadResource: true,
- )
- )
- )
- );
- },
- child: Text("Open Webview Browser")),
- );
- }
-}
diff --git a/ios/Classes/InAppWebView.swift b/ios/Classes/InAppWebView.swift
index 97ba8059..35c000a7 100755
--- a/ios/Classes/InAppWebView.swift
+++ b/ios/Classes/InAppWebView.swift
@@ -687,6 +687,8 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
var currentURL: URL?
var startPageTime: Int64 = 0
static var credentialsProposed: [URLCredential] = []
+ var lastScrollX: CGFloat = 0
+ var lastScrollY: CGFloat = 0
init(frame: CGRect, configuration: WKWebViewConfiguration, IABController: InAppBrowserWebViewController?, IAWController: FlutterWebViewController?) {
@@ -843,6 +845,8 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
scrollView.showsVerticalScrollIndicator = (options?.verticalScrollBarEnabled)!
scrollView.showsHorizontalScrollIndicator = (options?.horizontalScrollBarEnabled)!
+ scrollView.showsVerticalScrollIndicator = !(options?.disableVerticalScroll)!
+ scrollView.showsHorizontalScrollIndicator = !(options?.disableHorizontalScroll)!
// options.debuggingEnabled is always enabled for iOS.
@@ -1137,6 +1141,13 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
scrollView.showsHorizontalScrollIndicator = newOptions.horizontalScrollBarEnabled
}
+ if newOptionsMap["disableVerticalScroll"] != nil && options?.disableVerticalScroll != newOptions.disableVerticalScroll {
+ scrollView.showsVerticalScrollIndicator = !newOptions.disableVerticalScroll
+ }
+ if newOptionsMap["disableHorizontalScroll"] != nil && options?.disableHorizontalScroll != newOptions.disableHorizontalScroll {
+ scrollView.showsHorizontalScrollIndicator = !newOptions.disableHorizontalScroll
+ }
+
if #available(iOS 9.0, *) {
if newOptionsMap["allowsLinkPreview"] != nil && options?.allowsLinkPreview != newOptions.allowsLinkPreview {
allowsLinkPreview = newOptions.allowsLinkPreview
@@ -1785,12 +1796,29 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
+ let disableVerticalScroll = options?.disableVerticalScroll ?? false
+ let disableHorizontalScroll = options?.disableHorizontalScroll ?? false
+ if disableVerticalScroll && disableHorizontalScroll {
+ scrollView.contentOffset = CGPoint(x: lastScrollX, y: lastScrollY);
+ }
+ else if disableVerticalScroll {
+ if (scrollView.contentOffset.y >= 0 || scrollView.contentOffset.y < 0) {
+ scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: lastScrollY);
+ }
+ }
+ else if disableHorizontalScroll {
+ if (scrollView.contentOffset.x >= 0 || scrollView.contentOffset.x < 0) {
+ scrollView.contentOffset = CGPoint(x: lastScrollX, y: scrollView.contentOffset.y);
+ }
+ }
if navigationDelegate != nil {
let x = Int(scrollView.contentOffset.x / scrollView.contentScaleFactor)
let y = Int(scrollView.contentOffset.y / scrollView.contentScaleFactor)
onScrollChanged(x: x, y: y)
}
setNeedsLayout()
+ lastScrollX = scrollView.contentOffset.x
+ lastScrollY = scrollView.contentOffset.y
}
public func onLoadStart(url: String) {
diff --git a/ios/Classes/InAppWebViewOptions.swift b/ios/Classes/InAppWebViewOptions.swift
index e2995c7e..4755e654 100755
--- a/ios/Classes/InAppWebViewOptions.swift
+++ b/ios/Classes/InAppWebViewOptions.swift
@@ -32,6 +32,8 @@ public class InAppWebViewOptions: Options {
var incognito = false
var cacheEnabled = true
var transparentBackground = false
+ var disableVerticalScroll = false
+ var disableHorizontalScroll = false
var disallowOverScroll = false
var enableViewportScale = false
diff --git a/lib/src/webview_options.dart b/lib/src/webview_options.dart
index 36708500..ae2a60a5 100644
--- a/lib/src/webview_options.dart
+++ b/lib/src/webview_options.dart
@@ -101,12 +101,17 @@ class InAppWebViewOptions implements WebViewOptions, BrowserOptions, AndroidOpti
bool cacheEnabled;
///Set to `true` to make the background of the WebView transparent. If your app has a dark theme, this can prevent a white flash on initialization. The default value is `false`.
bool transparentBackground;
+ ///Set to `true` to disable vertical scroll. The default value is `false`.
+ bool disableVerticalScroll;
+ ///Set to `true` to disable horizontal scroll. The default value is `false`.
+ bool disableHorizontalScroll;
InAppWebViewOptions({this.useShouldOverrideUrlLoading = false, this.useOnLoadResource = false, this.useOnDownloadStart = false, this.useOnTargetBlank = false,
this.clearCache = false, this.userAgent = "", this.applicationNameForUserAgent = "", this.javaScriptEnabled = true, this.debuggingEnabled = false, this.javaScriptCanOpenWindowsAutomatically = false,
this.mediaPlaybackRequiresUserGesture = true, this.minimumFontSize, this.verticalScrollBarEnabled = true, this.horizontalScrollBarEnabled = true,
this.resourceCustomSchemes = const [], this.contentBlockers = const [], this.preferredContentMode = InAppWebViewUserPreferredContentMode.RECOMMENDED,
- this.useShouldInterceptAjaxRequest = false, this.useShouldInterceptFetchRequest = false, this.incognito = false, this.cacheEnabled = true, this.transparentBackground = false}) {
+ this.useShouldInterceptAjaxRequest = false, this.useShouldInterceptFetchRequest = false, this.incognito = false, this.cacheEnabled = true, this.transparentBackground = false,
+ this.disableVerticalScroll = false, this.disableHorizontalScroll = false}) {
if (this.minimumFontSize == null)
this.minimumFontSize = Platform.isAndroid ? 8 : 0;
assert(!this.resourceCustomSchemes.contains("http") && !this.resourceCustomSchemes.contains("https"));
@@ -140,7 +145,9 @@ class InAppWebViewOptions implements WebViewOptions, BrowserOptions, AndroidOpti
"useShouldInterceptFetchRequest": useShouldInterceptFetchRequest,
"incognito": incognito,
"cacheEnabled": cacheEnabled,
- "transparentBackground": transparentBackground
+ "transparentBackground": transparentBackground,
+ "disableVerticalScroll": disableVerticalScroll,
+ "disableHorizontalScroll": disableHorizontalScroll
};
}
@@ -178,6 +185,8 @@ class InAppWebViewOptions implements WebViewOptions, BrowserOptions, AndroidOpti
options.incognito = map["incognito"];
options.cacheEnabled = map["cacheEnabled"];
options.transparentBackground = map["transparentBackground"];
+ options.disableVerticalScroll = map["disableVerticalScroll"];
+ options.disableHorizontalScroll = map["disableHorizontalScroll"];
return options;
}
}