diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b930165..6871bb0e 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## 3.3.0 +- Updated API docs - Updated Android context menu workaround - Calling `onCreateContextMenu` event on iOS also when the context menu is disabled in order to have the same effect as Android - Added Android keyboard workaround to hide the keyboard when clicking other HTML elements, losing the focus on the previous input @@ -10,11 +11,13 @@ - Added `getCurrentWebViewPackage` static webview method on Android - Added `onPageCommitVisible` webview event - Added `androidShouldInterceptRequest`, `androidOnRenderProcessUnresponsive`, `androidOnRenderProcessResponsive`, `androidOnRenderProcessGone`, `androidOnFormResubmission`, `androidOnScaleChanged` Android events +- Added `toString()` method to various classes in order to have a better output instead of simply `Instance of ...` - Fixed `Print preview is not working? java.lang.IllegalStateException: Can print only from an activity` [#128](https://github.com/pichillilorenzo/flutter_inappwebview/issues/128) - Fixed `onJsAlert`, `onJsConfirm`, `onJsPrompt` for `InAppBrowser` on Android - Fixed `onActivityResult` for `InAppBrowser` on Android - Fixed `InAppBrowser.openWithSystemBrowser crash on iOS` [#358](https://github.com/pichillilorenzo/flutter_inappwebview/issues/358) - Fixed `Attempt to invoke virtual method 'java.util.Set java.util.HashMap.entrySet()' on a null object reference` [#367](https://github.com/pichillilorenzo/flutter_inappwebview/issues/367) +- Fixed missing `allowsAirPlayForMediaPlayback` iOS webview options implementation ### BREAKING CHANGES diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/ChromeCustomTabsActivity.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/ChromeCustomTabsActivity.java index 825497fa..80b82868 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/ChromeCustomTabsActivity.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/ChromeCustomTabsActivity.java @@ -29,13 +29,13 @@ public class ChromeCustomTabsActivity extends Activity implements MethodChannel. protected static final String LOG_TAG = "CustomTabsActivity"; public MethodChannel channel; public String uuid; - private CustomTabsIntent.Builder builder; - private ChromeCustomTabsOptions options; - private CustomTabActivityHelper customTabActivityHelper; - private CustomTabsSession customTabsSession; - private final int CHROME_CUSTOM_TAB_REQUEST_CODE = 100; - private boolean onChromeSafariBrowserOpened = false; - private boolean onChromeSafariBrowserCompletedInitialLoad = false; + public CustomTabsIntent.Builder builder; + public ChromeCustomTabsOptions options; + public CustomTabActivityHelper customTabActivityHelper; + public CustomTabsSession customTabsSession; + protected final int CHROME_CUSTOM_TAB_REQUEST_CODE = 100; + protected boolean onChromeSafariBrowserOpened = false; + protected boolean onChromeSafariBrowserCompletedInitialLoad = false; @Override protected void onCreate(Bundle savedInstanceState) { diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/ChromeCustomTabsOptions.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/ChromeCustomTabsOptions.java index 4024c4bd..005e9fa7 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/ChromeCustomTabsOptions.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/ChromeCustomTabsOptions.java @@ -1,69 +1,84 @@ package com.pichillilorenzo.flutter_inappwebview.ChromeCustomTabs; +import android.content.Intent; + import com.pichillilorenzo.flutter_inappwebview.Options; import java.util.HashMap; import java.util.Map; -public class ChromeCustomTabsOptions implements Options { +public class ChromeCustomTabsOptions implements Options { - final static String LOG_TAG = "ChromeCustomTabsOptions"; + final static String LOG_TAG = "ChromeCustomTabsOptions"; - public Boolean addDefaultShareMenuItem = true; - public Boolean showTitle = true; - public String toolbarBackgroundColor = ""; - public Boolean enableUrlBarHiding = false; - public Boolean instantAppsEnabled = false; - public String packageName; - public Boolean keepAliveEnabled = false; + public Boolean addDefaultShareMenuItem = true; + public Boolean showTitle = true; + public String toolbarBackgroundColor = ""; + public Boolean enableUrlBarHiding = false; + public Boolean instantAppsEnabled = false; + public String packageName; + public Boolean keepAliveEnabled = false; - @Override - public ChromeCustomTabsOptions parse(HashMap options) { - for (Map.Entry pair : options.entrySet()) { - String key = pair.getKey(); - Object value = pair.getValue(); - if (value == null) { - continue; - } + @Override + public ChromeCustomTabsOptions parse(Map options) { + for (Map.Entry pair : options.entrySet()) { + String key = pair.getKey(); + Object value = pair.getValue(); + if (value == null) { + continue; + } - switch (key) { - case "addDefaultShareMenuItem": - addDefaultShareMenuItem = (boolean) value; - break; - case "showTitle": - showTitle = (boolean) value; - break; - case "toolbarBackgroundColor": - toolbarBackgroundColor = (String) value; - break; - case "enableUrlBarHiding": - enableUrlBarHiding = (boolean) value; - break; - case "instantAppsEnabled": - instantAppsEnabled = (boolean) value; - break; - case "packageName": - packageName = (String) value; - break; - case "keepAliveEnabled": - keepAliveEnabled = (boolean) value; - break; - } - } - - return this; + switch (key) { + case "addDefaultShareMenuItem": + addDefaultShareMenuItem = (boolean) value; + break; + case "showTitle": + showTitle = (boolean) value; + break; + case "toolbarBackgroundColor": + toolbarBackgroundColor = (String) value; + break; + case "enableUrlBarHiding": + enableUrlBarHiding = (boolean) value; + break; + case "instantAppsEnabled": + instantAppsEnabled = (boolean) value; + break; + case "packageName": + packageName = (String) value; + break; + case "keepAliveEnabled": + keepAliveEnabled = (boolean) value; + break; + } } - @Override - public HashMap getHashMap() { - HashMap options = new HashMap<>(); - options.put("addDefaultShareMenuItem", addDefaultShareMenuItem); - options.put("showTitle", showTitle); - options.put("toolbarBackgroundColor", toolbarBackgroundColor); - options.put("enableUrlBarHiding", enableUrlBarHiding); - options.put("instantAppsEnabled", instantAppsEnabled); - options.put("packageName", packageName); - options.put("keepAliveEnabled", keepAliveEnabled); - return options; + return this; + } + + @Override + public Map toMap() { + Map options = new HashMap<>(); + options.put("addDefaultShareMenuItem", addDefaultShareMenuItem); + options.put("showTitle", showTitle); + options.put("toolbarBackgroundColor", toolbarBackgroundColor); + options.put("enableUrlBarHiding", enableUrlBarHiding); + options.put("instantAppsEnabled", instantAppsEnabled); + options.put("packageName", packageName); + options.put("keepAliveEnabled", keepAliveEnabled); + return options; + } + + @Override + public Map getRealOptions(ChromeCustomTabsActivity chromeCustomTabsActivity) { + Map realOptions = toMap(); + if (chromeCustomTabsActivity != null) { + Intent intent = chromeCustomTabsActivity.getIntent(); + if (intent != null) { + realOptions.put("packageName", intent.getPackage()); + realOptions.put("keepAliveEnabled", intent.hasExtra(CustomTabsHelper.EXTRA_CUSTOM_TABS_KEEP_ALIVE)); + } } + return realOptions; + } } diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/CustomTabsHelper.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/CustomTabsHelper.java index 1d33983f..a807e5f2 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/CustomTabsHelper.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeCustomTabs/CustomTabsHelper.java @@ -18,12 +18,12 @@ import java.util.List; * Helper class for Custom Tabs. */ public class CustomTabsHelper { - private static final String TAG = "CustomTabsHelper"; + protected static final String TAG = "CustomTabsHelper"; static final String STABLE_PACKAGE = "com.android.chrome"; static final String BETA_PACKAGE = "com.chrome.beta"; static final String DEV_PACKAGE = "com.chrome.dev"; static final String LOCAL_PACKAGE = "com.google.android.apps.chrome"; - private static final String EXTRA_CUSTOM_TABS_KEEP_ALIVE = + protected static final String EXTRA_CUSTOM_TABS_KEEP_ALIVE = "android.support.customtabs.extra.KEEP_ALIVE"; private static String sPackageNameToUse; diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeSafariBrowserManager.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeSafariBrowserManager.java index 8d6c7e66..b2ebde9e 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeSafariBrowserManager.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/ChromeSafariBrowserManager.java @@ -72,14 +72,14 @@ public class ChromeSafariBrowserManager implements MethodChannel.MethodCallHandl intent = new Intent(activity, ChromeCustomTabsActivity.class); } // check for webview fallback - else if (!CustomTabActivityHelper.isAvailable(activity) && !uuidFallback.isEmpty()) { + else if (!CustomTabActivityHelper.isAvailable(activity) && uuidFallback != null) { Log.d(LOG_TAG, "WebView fallback declared."); // overwrite with extras fallback parameters extras.putString("uuid", uuidFallback); if (optionsFallback != null) extras.putSerializable("options", optionsFallback); else - extras.putSerializable("options", (new InAppBrowserOptions()).getHashMap()); + extras.putSerializable("options", (Serializable) (new InAppBrowserOptions()).toMap()); intent = new Intent(activity, InAppBrowserActivity.class); } diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserActivity.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserActivity.java index f6708ed8..62ed8ee9 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserActivity.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserActivity.java @@ -707,12 +707,12 @@ public class InAppBrowserActivity extends AppCompatActivity implements MethodCha options = newOptions; } - public HashMap getOptions() { - HashMap webViewOptionsMap = webView.getOptions(); + public Map getOptions() { + Map webViewOptionsMap = webView.getOptions(); if (options == null || webViewOptionsMap == null) return null; - HashMap optionsMap = options.getHashMap(); + Map optionsMap = options.getRealOptions(this); optionsMap.putAll(webViewOptionsMap); return optionsMap; } diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserOptions.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserOptions.java index 733f4d42..9398a5e9 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserOptions.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppBrowser/InAppBrowserOptions.java @@ -5,7 +5,7 @@ import com.pichillilorenzo.flutter_inappwebview.Options; import java.util.HashMap; import java.util.Map; -public class InAppBrowserOptions implements Options { +public class InAppBrowserOptions implements Options { public static final String LOG_TAG = "InAppBrowserOptions"; @@ -20,7 +20,7 @@ public class InAppBrowserOptions implements Options { public Boolean progressBar = true; @Override - public InAppBrowserOptions parse(HashMap options) { + public InAppBrowserOptions parse(Map options) { for (Map.Entry pair : options.entrySet()) { String key = pair.getKey(); Object value = pair.getValue(); @@ -60,8 +60,8 @@ public class InAppBrowserOptions implements Options { } @Override - public HashMap getHashMap() { - HashMap options = new HashMap<>(); + public Map toMap() { + Map options = new HashMap<>(); options.put("hidden", hidden); options.put("toolbarTop", toolbarTop); options.put("toolbarTopBackgroundColor", toolbarTopBackgroundColor); @@ -72,4 +72,10 @@ public class InAppBrowserOptions implements Options { options.put("progressBar", progressBar); return options; } + + @Override + public Map getRealOptions(InAppBrowserActivity inAppBrowserActivity) { + Map realOptions = toMap(); + return realOptions; + } } diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebView.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebView.java index 0f243feb..7cbbf785 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebView.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebView.java @@ -1,7 +1,6 @@ package com.pichillilorenzo.flutter_inappwebview.InAppWebView; import android.content.Context; -import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; @@ -73,6 +72,7 @@ final public class InAppWebView extends InputAwareWebView { public InAppWebViewClient inAppWebViewClient; public InAppWebViewChromeClient inAppWebViewChromeClient; public InAppWebViewRenderProcessClient inAppWebViewRenderProcessClient; + public JavaScriptBridgeInterface javaScriptBridgeInterface; public InAppWebViewOptions options; public boolean isLoading = false; public OkHttpClient httpClient; @@ -632,7 +632,8 @@ final public class InAppWebView extends InputAwareWebView { httpClient = new OkHttpClient().newBuilder().build(); - addJavascriptInterface(new JavaScriptBridgeInterface((isFromInAppBrowserActivity) ? inAppBrowserActivity : flutterWebView), JavaScriptBridgeInterface.name); + javaScriptBridgeInterface = new JavaScriptBridgeInterface((isFromInAppBrowserActivity) ? inAppBrowserActivity : flutterWebView); + addJavascriptInterface(javaScriptBridgeInterface, JavaScriptBridgeInterface.name); inAppWebViewChromeClient = new InAppWebViewChromeClient((isFromInAppBrowserActivity) ? inAppBrowserActivity : flutterWebView); setWebChromeClient(inAppWebViewChromeClient); @@ -1373,8 +1374,8 @@ final public class InAppWebView extends InputAwareWebView { options = newOptions; } - public HashMap getOptions() { - return (options != null) ? options.getHashMap() : null; + public Map getOptions() { + return (options != null) ? options.getRealOptions(this) : null; } public void injectDeferredObject(String source, String jsWrapper, final MethodChannel.Result result) { diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebViewOptions.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebViewOptions.java index b7884bb4..aed179c2 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebViewOptions.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/InAppWebView/InAppWebViewOptions.java @@ -5,18 +5,17 @@ import android.util.Log; import android.view.View; import android.webkit.WebSettings; -import com.pichillilorenzo.flutter_inappwebview.ChromeCustomTabs.ChromeCustomTabsOptions; import com.pichillilorenzo.flutter_inappwebview.Options; -import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import static android.webkit.WebSettings.LayoutAlgorithm.NARROW_COLUMNS; import static android.webkit.WebSettings.LayoutAlgorithm.NORMAL; -public class InAppWebViewOptions implements Options { +public class InAppWebViewOptions implements Options { public static final String LOG_TAG = "InAppWebViewOptions"; @@ -99,7 +98,7 @@ public class InAppWebViewOptions implements Options { public Boolean useOnRenderProcessGone = false; @Override - public InAppWebViewOptions parse(HashMap options) { + public InAppWebViewOptions parse(Map options) { for (Map.Entry pair : options.entrySet()) { String key = pair.getKey(); Object value = pair.getValue(); @@ -343,8 +342,8 @@ public class InAppWebViewOptions implements Options { } @Override - public HashMap getHashMap() { - HashMap options = new HashMap<>(); + public Map toMap() { + Map options = new HashMap<>(); options.put("useShouldOverrideUrlLoading", useShouldOverrideUrlLoading); options.put("useOnLoadResource", useOnLoadResource); options.put("useOnDownloadStart", useOnDownloadStart); @@ -424,9 +423,83 @@ public class InAppWebViewOptions implements Options { return options; } + @Override + public Map getRealOptions(InAppWebView webView) { + Map realOptions = toMap(); + if (webView != null) { + WebSettings settings = webView.getSettings(); + realOptions.put("userAgent", settings.getUserAgentString()); + realOptions.put("javaScriptEnabled", settings.getJavaScriptEnabled()); + realOptions.put("javaScriptCanOpenWindowsAutomatically", settings.getJavaScriptCanOpenWindowsAutomatically()); + realOptions.put("mediaPlaybackRequiresUserGesture", settings.getMediaPlaybackRequiresUserGesture()); + realOptions.put("minimumFontSize", settings.getMinimumFontSize()); + realOptions.put("verticalScrollBarEnabled", webView.isVerticalScrollBarEnabled()); + realOptions.put("horizontalScrollBarEnabled", webView.isHorizontalScrollBarEnabled()); + realOptions.put("textZoom", settings.getTextZoom()); + realOptions.put("builtInZoomControls", settings.getBuiltInZoomControls()); + realOptions.put("supportZoom", settings.supportZoom()); + realOptions.put("displayZoomControls", settings.getDisplayZoomControls()); + realOptions.put("databaseEnabled", settings.getDatabaseEnabled()); + realOptions.put("domStorageEnabled", settings.getDomStorageEnabled()); + realOptions.put("useWideViewPort", settings.getUseWideViewPort()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + realOptions.put("safeBrowsingEnabled", settings.getSafeBrowsingEnabled()); + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + realOptions.put("mixedContentMode", settings.getMixedContentMode()); + } + realOptions.put("allowContentAccess", settings.getAllowContentAccess()); + realOptions.put("allowFileAccess", settings.getAllowFileAccess()); + realOptions.put("allowFileAccessFromFileURLs", settings.getAllowFileAccessFromFileURLs()); + realOptions.put("allowUniversalAccessFromFileURLs", settings.getAllowUniversalAccessFromFileURLs()); + realOptions.put("blockNetworkImage", settings.getBlockNetworkImage()); + realOptions.put("blockNetworkLoads", settings.getBlockNetworkLoads()); + realOptions.put("cacheMode", settings.getCacheMode()); + realOptions.put("cursiveFontFamily", settings.getCursiveFontFamily()); + realOptions.put("defaultFixedFontSize", settings.getDefaultFixedFontSize()); + realOptions.put("defaultFontSize", settings.getDefaultFontSize()); + realOptions.put("defaultTextEncodingName", settings.getDefaultTextEncodingName()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + realOptions.put("disabledActionModeMenuItems", settings.getDisabledActionModeMenuItems()); + } + realOptions.put("fantasyFontFamily", settings.getFantasyFontFamily()); + realOptions.put("fixedFontFamily", settings.getFixedFontFamily()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + realOptions.put("forceDark", settings.getForceDark()); + } + realOptions.put("layoutAlgorithm", settings.getLayoutAlgorithm().name()); + realOptions.put("loadWithOverviewMode", settings.getLoadWithOverviewMode()); + realOptions.put("loadsImagesAutomatically", settings.getLoadsImagesAutomatically()); + realOptions.put("minimumLogicalFontSize", settings.getMinimumLogicalFontSize()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + realOptions.put("offscreenPreRaster", settings.getOffscreenPreRaster()); + } + realOptions.put("sansSerifFontFamily", settings.getSansSerifFontFamily()); + realOptions.put("serifFontFamily", settings.getSerifFontFamily()); + realOptions.put("standardFontFamily", settings.getStandardFontFamily()); + realOptions.put("saveFormData", settings.getSaveFormData()); + realOptions.put("supportMultipleWindows", settings.supportMultipleWindows()); + realOptions.put("overScrollMode", webView.getOverScrollMode()); + realOptions.put("scrollBarStyle", webView.getScrollBarStyle()); + realOptions.put("verticalScrollbarPosition", webView.getVerticalScrollbarPosition()); + realOptions.put("scrollBarDefaultDelayBeforeFade", webView.getScrollBarDefaultDelayBeforeFade()); + realOptions.put("scrollbarFadingEnabled", webView.isScrollbarFadingEnabled()); + realOptions.put("scrollBarFadeDuration", webView.getScrollBarFadeDuration()); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + Map rendererPriorityPolicy = new HashMap<>(); + rendererPriorityPolicy.put("rendererRequestedPriority", webView.getRendererRequestedPriority()); + rendererPriorityPolicy.put("waivedWhenNotVisible", webView.getRendererPriorityWaivedWhenNotVisible()); + realOptions.put("rendererPriorityPolicy", rendererPriorityPolicy); + } + } + return realOptions; + } + private void setLayoutAlgorithm(String value) { if (value != null) { switch (value) { + case "NARROW_COLUMNS": + layoutAlgorithm = NARROW_COLUMNS; case "NORMAL": layoutAlgorithm = NORMAL; case "TEXT_AUTOSIZING": @@ -451,6 +524,8 @@ public class InAppWebViewOptions implements Options { } else { return "NORMAL"; } + case NARROW_COLUMNS: + return "NARROW_COLUMNS"; } } return null; diff --git a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/Options.java b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/Options.java index 2d21ae3c..bd5440ac 100755 --- a/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/Options.java +++ b/android/src/main/java/com/pichillilorenzo/flutter_inappwebview/Options.java @@ -1,9 +1,10 @@ package com.pichillilorenzo.flutter_inappwebview; -import java.util.HashMap; +import java.util.Map; -public interface Options { +public interface Options { static String LOG_TAG = "Options"; - public Options parse(HashMap options); - public HashMap getHashMap(); + public Options parse(Map options); + public Map toMap(); + public Map getRealOptions(T webView); } diff --git a/example/.flutter-plugins-dependencies b/example/.flutter-plugins-dependencies index 09e9752d..5891ba58 100755 --- a/example/.flutter-plugins-dependencies +++ b/example/.flutter-plugins-dependencies @@ -1 +1 @@ -{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"e2e","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/e2e-0.2.4+4/","dependencies":[]},{"name":"flutter_inappwebview","path":"/Users/lorenzopichilli/Desktop/flutter_inappwebview/","dependencies":[]},{"name":"permission_handler","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-5.0.0+hotfix.6/","dependencies":[]}],"android":[{"name":"e2e","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/e2e-0.2.4+4/","dependencies":[]},{"name":"flutter_inappwebview","path":"/Users/lorenzopichilli/Desktop/flutter_inappwebview/","dependencies":[]},{"name":"permission_handler","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-5.0.0+hotfix.6/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"e2e","dependencies":[]},{"name":"flutter_inappwebview","dependencies":[]},{"name":"permission_handler","dependencies":[]}],"date_created":"2020-05-29 10:25:22.515235","version":"1.17.1"} \ No newline at end of file +{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"e2e","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/e2e-0.2.4+4/","dependencies":[]},{"name":"flutter_inappwebview","path":"/Users/lorenzopichilli/Desktop/flutter_inappwebview/","dependencies":[]},{"name":"permission_handler","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-5.0.0+hotfix.6/","dependencies":[]}],"android":[{"name":"e2e","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/e2e-0.2.4+4/","dependencies":[]},{"name":"flutter_inappwebview","path":"/Users/lorenzopichilli/Desktop/flutter_inappwebview/","dependencies":[]},{"name":"permission_handler","path":"/Users/lorenzopichilli/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-5.0.0+hotfix.6/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"e2e","dependencies":[]},{"name":"flutter_inappwebview","dependencies":[]},{"name":"permission_handler","dependencies":[]}],"date_created":"2020-05-29 19:53:44.213613","version":"1.17.1"} \ No newline at end of file diff --git a/example/lib/chrome_safari_browser_example.screen.dart b/example/lib/chrome_safari_browser_example.screen.dart index d6cddd97..8bae4cc7 100755 --- a/example/lib/chrome_safari_browser_example.screen.dart +++ b/example/lib/chrome_safari_browser_example.screen.dart @@ -4,7 +4,7 @@ import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'main.dart'; class MyChromeSafariBrowser extends ChromeSafariBrowser { - MyChromeSafariBrowser(browserFallback) : super(bFallback: browserFallback); + MyChromeSafariBrowser({browserFallback}) : super(bFallback: browserFallback); @override void onOpened() { @@ -24,23 +24,23 @@ class MyChromeSafariBrowser extends ChromeSafariBrowser { class ChromeSafariBrowserExampleScreen extends StatefulWidget { final ChromeSafariBrowser browser = - new MyChromeSafariBrowser(new InAppBrowser()); + MyChromeSafariBrowser(browserFallback: InAppBrowser()); @override _ChromeSafariBrowserExampleScreenState createState() => - new _ChromeSafariBrowserExampleScreenState(); + _ChromeSafariBrowserExampleScreenState(); } class _ChromeSafariBrowserExampleScreenState extends State { @override void initState() { - widget.browser.addMenuItem(new ChromeSafariBrowserMenuItem(id: 1, label: 'Custom item menu 1', action: (url, title) { + widget.browser.addMenuItem(ChromeSafariBrowserMenuItem(id: 1, label: 'Custom item menu 1', action: (url, title) { print('Custom item menu 1 clicked!'); print(url); print(title); })); - widget.browser.addMenuItem(new ChromeSafariBrowserMenuItem(id: 2, label: 'Custom item menu 2', action: (url, title) { + widget.browser.addMenuItem(ChromeSafariBrowserMenuItem(id: 2, label: 'Custom item menu 2', action: (url, title) { print('Custom item menu 2 clicked!'); print(url); print(title); diff --git a/ios/Classes/ChromeSafariBrowserManager.swift b/ios/Classes/ChromeSafariBrowserManager.swift index a22c6ce6..114bc35a 100755 --- a/ios/Classes/ChromeSafariBrowserManager.swift +++ b/ios/Classes/ChromeSafariBrowserManager.swift @@ -39,10 +39,10 @@ public class ChromeSafariBrowserManager: NSObject, FlutterPlugin { let url = arguments!["url"] as! String let options = arguments!["options"] as! [String: Any?] let menuItemList = arguments!["menuItemList"] as! [[String: Any]] - let uuidFallback: String = arguments!["uuidFallback"] as! String - let headersFallback = arguments!["headersFallback"] as! [String: String] - let optionsFallback = arguments!["optionsFallback"] as! [String: Any?] - let contextMenuFallback = arguments!["contextMenuFallback"] as! [String: Any] + let uuidFallback = arguments!["uuidFallback"] as? String + let headersFallback = arguments!["headersFallback"] as? [String: String] + let optionsFallback = arguments!["optionsFallback"] as? [String: Any?] + let contextMenuFallback = arguments!["contextMenuFallback"] as? [String: Any] open(uuid: uuid, url: url, options: options, menuItemList: menuItemList, uuidFallback: uuidFallback, headersFallback: headersFallback, optionsFallback: optionsFallback, contextMenuFallback: contextMenuFallback, result: result) break default: @@ -51,7 +51,7 @@ public class ChromeSafariBrowserManager: NSObject, FlutterPlugin { } } - public func open(uuid: String, url: String, options: [String: Any?], menuItemList: [[String: Any]], uuidFallback: String, headersFallback: [String: String], optionsFallback: [String: Any?], contextMenuFallback: [String: Any], result: @escaping FlutterResult) { + public func open(uuid: String, url: String, options: [String: Any?], menuItemList: [[String: Any]], uuidFallback: String?, headersFallback: [String: String]?, optionsFallback: [String: Any?]?, contextMenuFallback: [String: Any]?, result: @escaping FlutterResult) { let absoluteUrl = URL(string: url)!.absoluteURL if self.previousStatusBarStyle == -1 { @@ -106,7 +106,7 @@ public class ChromeSafariBrowserManager: NSObject, FlutterPlugin { return } - SwiftFlutterPlugin.instance!.inAppBrowserManager!.openUrl(uuid: uuidFallback, url: url, options: optionsFallback, headers: headersFallback, contextMenu: contextMenuFallback) + SwiftFlutterPlugin.instance!.inAppBrowserManager!.openUrl(uuid: uuidFallback!, url: url, options: optionsFallback ?? [:], headers: headersFallback ?? [:], contextMenu: contextMenuFallback ?? [:]) } } } diff --git a/ios/Classes/InAppBrowserOptions.swift b/ios/Classes/InAppBrowserOptions.swift index 5e4ab7ff..0eee78d3 100755 --- a/ios/Classes/InAppBrowserOptions.swift +++ b/ios/Classes/InAppBrowserOptions.swift @@ -8,7 +8,7 @@ import Foundation @objcMembers -public class InAppBrowserOptions: Options { +public class InAppBrowserOptions: Options { var hidden = false var toolbarTop = true @@ -29,5 +29,12 @@ public class InAppBrowserOptions: Options { super.init() } + override func getRealOptions(obj: InAppBrowserWebViewController?) -> [String: Any?] { + var realOptions: [String: Any?] = toMap() + if let inAppBrowserWebViewController = obj { + realOptions["presentationStyle"] = inAppBrowserWebViewController.modalPresentationStyle.rawValue + realOptions["transitionStyle"] = inAppBrowserWebViewController.modalTransitionStyle.rawValue + } + return realOptions + } } - diff --git a/ios/Classes/InAppBrowserWebViewController.swift b/ios/Classes/InAppBrowserWebViewController.swift index da86e901..2d71f313 100755 --- a/ios/Classes/InAppBrowserWebViewController.swift +++ b/ios/Classes/InAppBrowserWebViewController.swift @@ -688,11 +688,12 @@ public class InAppBrowserWebViewController: UIViewController, FlutterPlugin, UIS } public func getOptions() -> [String: Any?]? { - if (self.browserOptions == nil || self.webView.getOptions() == nil) { + let webViewOptionsMap = self.webView.getOptions() + if (self.browserOptions == nil || webViewOptionsMap == nil) { return nil } - var optionsMap = self.browserOptions!.getHashMap() - optionsMap.merge(self.webView.getOptions()!, uniquingKeysWith: { (current, _) in current }) + var optionsMap = self.browserOptions!.getRealOptions(obj: self) + optionsMap.merge(webViewOptionsMap!, uniquingKeysWith: { (current, _) in current }) return optionsMap } diff --git a/ios/Classes/InAppWebView.swift b/ios/Classes/InAppWebView.swift index ea06081a..7a346b68 100755 --- a/ios/Classes/InAppWebView.swift +++ b/ios/Classes/InAppWebView.swift @@ -1056,6 +1056,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi allowsBackForwardNavigationGestures = (options?.allowsBackForwardNavigationGestures)! if #available(iOS 9.0, *) { allowsLinkPreview = (options?.allowsLinkPreview)! + configuration.allowsAirPlayForMediaPlayback = (options?.allowsAirPlayForMediaPlayback)! configuration.allowsPictureInPictureMediaPlayback = (options?.allowsPictureInPictureMediaPlayback)! if (options?.applicationNameForUserAgent != nil && (options?.applicationNameForUserAgent)! != "") { configuration.applicationNameForUserAgent = (options?.applicationNameForUserAgent)! @@ -1075,7 +1076,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi var dataDetectorTypes = WKDataDetectorTypes.init(rawValue: 0) for type in options?.dataDetectorTypes ?? [] { - let dataDetectorType = getDataDetectorType(type: type) + let dataDetectorType = InAppWebView.getDataDetectorType(type: type) dataDetectorTypes = WKDataDetectorTypes(rawValue: dataDetectorTypes.rawValue | dataDetectorType.rawValue) } configuration.dataDetectorTypes = dataDetectorTypes @@ -1094,7 +1095,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi scrollView.showsVerticalScrollIndicator = (options?.verticalScrollBarEnabled)! scrollView.showsHorizontalScrollIndicator = (options?.horizontalScrollBarEnabled)! - scrollView.decelerationRate = getDecelerationRate(type: (options?.decelerationRate)!) + scrollView.decelerationRate = InAppWebView.getDecelerationRate(type: (options?.decelerationRate)!) scrollView.alwaysBounceVertical = (options?.alwaysBounceVertical)! scrollView.alwaysBounceHorizontal = (options?.alwaysBounceHorizontal)! scrollView.scrollsToTop = (options?.scrollsToTop)! @@ -1110,7 +1111,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi } @available(iOS 10.0, *) - public func getDataDetectorType(type: String) -> WKDataDetectorTypes { + static public func getDataDetectorType(type: String) -> WKDataDetectorTypes { switch type { case "NONE": return WKDataDetectorTypes.init(rawValue: 0) @@ -1137,7 +1138,44 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi } } - public func getDecelerationRate(type: String) -> UIScrollView.DecelerationRate { + @available(iOS 10.0, *) + static public func getDataDetectorTypeString(type: WKDataDetectorTypes) -> [String] { + var dataDetectorTypeString: [String] = [] + if type.contains(.all) { + dataDetectorTypeString.append("ALL") + } else { + if type.contains(.phoneNumber) { + dataDetectorTypeString.append("PHONE_NUMBER") + } + if type.contains(.link) { + dataDetectorTypeString.append("LINK") + } + if type.contains(.address) { + dataDetectorTypeString.append("ADDRESS") + } + if type.contains(.calendarEvent) { + dataDetectorTypeString.append("CALENDAR_EVENT") + } + if type.contains(.trackingNumber) { + dataDetectorTypeString.append("TRACKING_NUMBER") + } + if type.contains(.flightNumber) { + dataDetectorTypeString.append("FLIGHT_NUMBER") + } + if type.contains(.lookupSuggestion) { + dataDetectorTypeString.append("LOOKUP_SUGGESTION") + } + if type.contains(.spotlightSuggestion) { + dataDetectorTypeString.append("SPOTLIGHT_SUGGESTION") + } + } + if dataDetectorTypeString.count == 0 { + dataDetectorTypeString = ["NONE"] + } + return dataDetectorTypeString + } + + static public func getDecelerationRate(type: String) -> UIScrollView.DecelerationRate { switch type { case "NORMAL": return .normal @@ -1148,6 +1186,17 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi } } + static public func getDecelerationRateString(type: UIScrollView.DecelerationRate) -> String { + switch type { + case .normal: + return "NORMAL" + case .fast: + return "FAST" + default: + return "NORMAL" + } + } + public static func preWKWebViewConfiguration(options: InAppWebViewOptions?) -> WKWebViewConfiguration { let configuration = WKWebViewConfiguration() @@ -1403,10 +1452,6 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi allowsBackForwardNavigationGestures = newOptions.allowsBackForwardNavigationGestures } - if newOptionsMap["allowsInlineMediaPlayback"] != nil && options?.allowsInlineMediaPlayback != newOptions.allowsInlineMediaPlayback { - configuration.allowsInlineMediaPlayback = newOptions.allowsInlineMediaPlayback - } - if newOptionsMap["javaScriptCanOpenWindowsAutomatically"] != nil && options?.javaScriptCanOpenWindowsAutomatically != newOptions.javaScriptCanOpenWindowsAutomatically { configuration.preferences.javaScriptCanOpenWindowsAutomatically = newOptions.javaScriptCanOpenWindowsAutomatically } @@ -1431,7 +1476,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi if newOptionsMap["dataDetectorTypes"] != nil && options?.dataDetectorTypes != newOptions.dataDetectorTypes { var dataDetectorTypes = WKDataDetectorTypes.init(rawValue: 0) for type in newOptions.dataDetectorTypes { - let dataDetectorType = getDataDetectorType(type: type) + let dataDetectorType = InAppWebView.getDataDetectorType(type: type) dataDetectorTypes = WKDataDetectorTypes(rawValue: dataDetectorTypes.rawValue | dataDetectorType.rawValue) } configuration.dataDetectorTypes = dataDetectorTypes @@ -1465,7 +1510,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi } if newOptionsMap["decelerationRate"] != nil && options?.decelerationRate != newOptions.decelerationRate { - scrollView.decelerationRate = getDecelerationRate(type: newOptions.decelerationRate) + scrollView.decelerationRate = InAppWebView.getDecelerationRate(type: newOptions.decelerationRate) } if newOptionsMap["alwaysBounceVertical"] != nil && options?.alwaysBounceVertical != newOptions.alwaysBounceVertical { scrollView.alwaysBounceVertical = newOptions.alwaysBounceVertical @@ -1490,6 +1535,9 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi if newOptionsMap["allowsLinkPreview"] != nil && options?.allowsLinkPreview != newOptions.allowsLinkPreview { allowsLinkPreview = newOptions.allowsLinkPreview } + if newOptionsMap["allowsAirPlayForMediaPlayback"] != nil && options?.allowsAirPlayForMediaPlayback != newOptions.allowsAirPlayForMediaPlayback { + configuration.allowsAirPlayForMediaPlayback = newOptions.allowsAirPlayForMediaPlayback + } if newOptionsMap["allowsPictureInPictureMediaPlayback"] != nil && options?.allowsPictureInPictureMediaPlayback != newOptions.allowsPictureInPictureMediaPlayback { configuration.allowsPictureInPictureMediaPlayback = newOptions.allowsPictureInPictureMediaPlayback } @@ -1534,7 +1582,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi if (self.options == nil) { return nil } - return self.options!.getHashMap() + return self.options!.getRealOptions(obj: self) } public func clearCache() { diff --git a/ios/Classes/InAppWebViewOptions.swift b/ios/Classes/InAppWebViewOptions.swift index 7a0a0382..00d92d48 100755 --- a/ios/Classes/InAppWebViewOptions.swift +++ b/ios/Classes/InAppWebViewOptions.swift @@ -9,7 +9,7 @@ import Foundation import WebKit @objcMembers -public class InAppWebViewOptions: Options { +public class InAppWebViewOptions: Options { var useShouldOverrideUrlLoading = false var useOnLoadResource = false @@ -63,4 +63,47 @@ public class InAppWebViewOptions: Options { super.init() } + override func getRealOptions(obj: InAppWebView?) -> [String: Any?] { + var realOptions: [String: Any?] = toMap() + if let webView = obj { + let configuration = webView.configuration + if #available(iOS 9.0, *) { + realOptions["userAgent"] = webView.customUserAgent + realOptions["applicationNameForUserAgent"] = configuration.applicationNameForUserAgent + realOptions["allowsAirPlayForMediaPlayback"] = configuration.allowsAirPlayForMediaPlayback + realOptions["allowsLinkPreview"] = webView.allowsLinkPreview + realOptions["allowsPictureInPictureMediaPlayback"] = configuration.allowsPictureInPictureMediaPlayback + } + realOptions["javaScriptEnabled"] = configuration.preferences.javaScriptEnabled + realOptions["javaScriptCanOpenWindowsAutomatically"] = configuration.preferences.javaScriptCanOpenWindowsAutomatically + if #available(iOS 10.0, *) { + realOptions["mediaPlaybackRequiresUserGesture"] = configuration.mediaTypesRequiringUserActionForPlayback == .all + realOptions["ignoresViewportScaleLimits"] = configuration.ignoresViewportScaleLimits + realOptions["dataDetectorTypes"] = InAppWebView.getDataDetectorTypeString(type: configuration.dataDetectorTypes) + } else { + realOptions["mediaPlaybackRequiresUserGesture"] = configuration.mediaPlaybackRequiresUserAction + } + realOptions["minimumFontSize"] = configuration.preferences.minimumFontSize + realOptions["suppressesIncrementalRendering"] = configuration.suppressesIncrementalRendering + realOptions["allowsBackForwardNavigationGestures"] = webView.allowsBackForwardNavigationGestures + realOptions["allowsInlineMediaPlayback"] = configuration.allowsInlineMediaPlayback + if #available(iOS 13.0, *) { + realOptions["isFraudulentWebsiteWarningEnabled"] = configuration.preferences.isFraudulentWebsiteWarningEnabled + realOptions["preferredContentMode"] = configuration.defaultWebpagePreferences.preferredContentMode.rawValue + realOptions["automaticallyAdjustsScrollIndicatorInsets"] = webView.scrollView.automaticallyAdjustsScrollIndicatorInsets + } + realOptions["selectionGranularity"] = configuration.selectionGranularity.rawValue + if #available(iOS 11.0, *) { + realOptions["accessibilityIgnoresInvertColors"] = webView.accessibilityIgnoresInvertColors + } + realOptions["decelerationRate"] = InAppWebView.getDecelerationRateString(type: webView.scrollView.decelerationRate) + realOptions["alwaysBounceVertical"] = webView.scrollView.alwaysBounceVertical + realOptions["alwaysBounceHorizontal"] = webView.scrollView.alwaysBounceHorizontal + realOptions["scrollsToTop"] = webView.scrollView.scrollsToTop + realOptions["isPagingEnabled"] = webView.scrollView.isPagingEnabled + realOptions["maximumZoomScale"] = webView.scrollView.maximumZoomScale + realOptions["minimumZoomScale"] = webView.scrollView.minimumZoomScale + } + return realOptions + } } diff --git a/ios/Classes/Options.swift b/ios/Classes/Options.swift index 2d869c29..1d1d61b3 100755 --- a/ios/Classes/Options.swift +++ b/ios/Classes/Options.swift @@ -8,7 +8,7 @@ import Foundation @objcMembers -public class Options: NSObject { +public class Options: NSObject { override init(){ super.init() @@ -23,7 +23,7 @@ public class Options: NSObject { return self } - func getHashMap() -> [String: Any?] { + func toMap() -> [String: Any?] { var options: [String: Any?] = [:] var counts = UInt32(); let properties = class_copyPropertyList(object_getClass(self), &counts); @@ -38,4 +38,9 @@ public class Options: NSObject { free(properties) return options } + + func getRealOptions(obj: T?) -> [String: Any?] { + let realOptions: [String: Any?] = toMap() + return realOptions + } } diff --git a/ios/Classes/SafariBrowserOptions.swift b/ios/Classes/SafariBrowserOptions.swift index 714beded..d3893438 100755 --- a/ios/Classes/SafariBrowserOptions.swift +++ b/ios/Classes/SafariBrowserOptions.swift @@ -7,8 +7,9 @@ import Foundation +@available(iOS 9.0, *) @objcMembers -public class SafariBrowserOptions: Options { +public class SafariBrowserOptions: Options { var entersReaderIfAvailable = false var barCollapsingEnabled = false @@ -22,4 +23,17 @@ public class SafariBrowserOptions: Options { super.init() } + override func getRealOptions(obj: SafariViewController?) -> [String: Any?] { + var realOptions: [String: Any?] = toMap() + if let safariViewController = obj { + if #available(iOS 11.0, *) { + realOptions["entersReaderIfAvailable"] = safariViewController.configuration.entersReaderIfAvailable + realOptions["barCollapsingEnabled"] = safariViewController.configuration.barCollapsingEnabled + realOptions["dismissButtonStyle"] = safariViewController.dismissButtonStyle.rawValue + } + realOptions["presentationStyle"] = safariViewController.modalPresentationStyle.rawValue + realOptions["transitionStyle"] = safariViewController.modalTransitionStyle.rawValue + } + return realOptions + } } diff --git a/lib/src/chrome_safari_browser.dart b/lib/src/chrome_safari_browser.dart index 72e77d8c..d6a8152d 100755 --- a/lib/src/chrome_safari_browser.dart +++ b/lib/src/chrome_safari_browser.dart @@ -17,7 +17,8 @@ class ChromeSafariBrowser { Map _menuItems = new HashMap(); bool _isOpened = false; MethodChannel _channel; - static const MethodChannel _sharedChannel = const MethodChannel('com.pichillilorenzo/flutter_chromesafaribrowser'); + static const MethodChannel _sharedChannel = + const MethodChannel('com.pichillilorenzo/flutter_chromesafaribrowser'); ///Initialize the [ChromeSafariBrowser] instance with an [InAppBrowser] fallback instance or `null`. ChromeSafariBrowser({bFallback}) { @@ -73,10 +74,7 @@ class ChromeSafariBrowser { List> menuItemList = new List(); _menuItems.forEach((key, value) { - menuItemList.add({ - "id": value.id, - "label": value.label - }); + menuItemList.add({"id": value.id, "label": value.label}); }); Map args = {}; @@ -84,11 +82,11 @@ class ChromeSafariBrowser { args.putIfAbsent('url', () => url); args.putIfAbsent('options', () => options?.toMap() ?? {}); args.putIfAbsent('menuItemList', () => menuItemList); - args.putIfAbsent('uuidFallback', - () => (browserFallback != null) ? browserFallback.uuid : ''); - args.putIfAbsent('headersFallback', () => headersFallback); + args.putIfAbsent('uuidFallback', () => browserFallback?.uuid); + args.putIfAbsent('headersFallback', () => headersFallback ?? {}); args.putIfAbsent('optionsFallback', () => optionsFallback?.toMap() ?? {}); - args.putIfAbsent('contextMenuFallback', () => browserFallback?.contextMenu?.toMap() ?? {}); + args.putIfAbsent('contextMenuFallback', + () => browserFallback?.contextMenu?.toMap() ?? {}); await _sharedChannel.invokeMethod('open', args); this._isOpened = true; } @@ -142,10 +140,30 @@ class ChromeSafariBrowser { } } +///Class that represents a custom menu item for a [ChromeSafariBrowser] instance. class ChromeSafariBrowserMenuItem { + ///The menu item id int id; + + ///The label of the menu item String label; + + ///Callback function to be invoked when the menu item is clicked final void Function(String url, String title) action; - ChromeSafariBrowserMenuItem({@required this.id, @required this.label, @required this.action}); -} \ No newline at end of file + ChromeSafariBrowserMenuItem( + {@required this.id, @required this.label, @required this.action}); + + Map toMap() { + return {"id": id, "label": label}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } +} diff --git a/lib/src/context_menu.dart b/lib/src/context_menu.dart index a5452bed..fccb8304 100644 --- a/lib/src/context_menu.dart +++ b/lib/src/context_menu.dart @@ -7,11 +7,11 @@ import 'types.dart'; /// ///**NOTE**: To make it work properly on Android, JavaScript should be enabled! class ContextMenu { - ///Event fired when the context menu for this WebView is being built. /// ///[hitTestResult] represents the hit result for hitting an HTML elements. - final void Function(InAppWebViewHitTestResult hitTestResult) onCreateContextMenu; + final void Function(InAppWebViewHitTestResult hitTestResult) + onCreateContextMenu; ///Event fired when the context menu for this WebView is being hidden. final void Function() onHideContextMenu; @@ -19,17 +19,17 @@ class ContextMenu { ///Event fired when a context menu item has been clicked. /// ///[contextMenuItemClicked] represents the [ContextMenuItem] clicked. - final void Function(ContextMenuItem contextMenuItemClicked) onContextMenuActionItemClicked; + final void Function(ContextMenuItem contextMenuItemClicked) + onContextMenuActionItemClicked; ///List of the custom [ContextMenuItem]. List menuItems = List(); - ContextMenu({ - this.menuItems, - this.onCreateContextMenu, - this.onHideContextMenu, - this.onContextMenuActionItemClicked - }); + ContextMenu( + {this.menuItems, + this.onCreateContextMenu, + this.onHideContextMenu, + this.onContextMenuActionItemClicked}); Map toMap() { return { @@ -46,21 +46,24 @@ class ContextMenu { class ContextMenuItem { ///Android menu item ID. int androidId; + ///iOS menu item ID. String iosId; + ///Menu item title. String title; + ///Menu item action that will be called when an user clicks on it. Function() action; - ContextMenuItem({@required this.androidId, @required this.iosId, @required this.title, this.action}); + ContextMenuItem( + {@required this.androidId, + @required this.iosId, + @required this.title, + this.action}); Map toMap() { - return { - "androidId": androidId, - "iosId": iosId, - "title": title - }; + return {"androidId": androidId, "iosId": iosId, "title": title}; } Map toJson() { diff --git a/lib/src/cookie_manager.dart b/lib/src/cookie_manager.dart index 007ff84a..defd8c7a 100755 --- a/lib/src/cookie_manager.dart +++ b/lib/src/cookie_manager.dart @@ -22,7 +22,7 @@ class CookieManager { static CookieManager _init() { _channel.setMethodCallHandler(_handleMethod); - _instance = new CookieManager(); + _instance = CookieManager(); return _instance; } diff --git a/lib/src/headless_in_app_webview.dart b/lib/src/headless_in_app_webview.dart index 95600195..57dff8a6 100644 --- a/lib/src/headless_in_app_webview.dart +++ b/lib/src/headless_in_app_webview.dart @@ -12,61 +12,61 @@ import 'in_app_webview_controller.dart'; class HeadlessInAppWebView implements WebView { String uuid; bool _isDisposed = true; - static const MethodChannel _sharedChannel = const MethodChannel('com.pichillilorenzo/flutter_headless_inappwebview'); + static const MethodChannel _sharedChannel = + const MethodChannel('com.pichillilorenzo/flutter_headless_inappwebview'); ///WebView Controller that can be used to access the [InAppWebViewController] API. InAppWebViewController webViewController; - HeadlessInAppWebView({ - this.onWebViewCreated, - this.onLoadStart, - this.onLoadStop, - this.onLoadError, - this.onLoadHttpError, - this.onProgressChanged, - this.onConsoleMessage, - this.shouldOverrideUrlLoading, - this.onLoadResource, - this.onScrollChanged, - this.onDownloadStart, - this.onLoadResourceCustomScheme, - this.onCreateWindow, - this.onJsAlert, - this.onJsConfirm, - this.onJsPrompt, - this.onReceivedHttpAuthRequest, - this.onReceivedServerTrustAuthRequest, - this.onReceivedClientCertRequest, - this.onFindResultReceived, - this.shouldInterceptAjaxRequest, - this.onAjaxReadyStateChange, - this.onAjaxProgress, - this.shouldInterceptFetchRequest, - this.onUpdateVisitedHistory, - this.onPrint, - this.onLongPressHitTestResult, - this.onEnterFullscreen, - this.onExitFullscreen, - this.onPageCommitVisible, - this.androidOnSafeBrowsingHit, - this.androidOnPermissionRequest, - this.androidOnGeolocationPermissionsShowPrompt, - this.androidOnGeolocationPermissionsHidePrompt, - this.androidShouldInterceptRequest, - this.androidOnRenderProcessGone, - this.androidOnRenderProcessResponsive, - this.androidOnRenderProcessUnresponsive, - this.androidOnFormResubmission, - this.androidOnScaleChanged, - this.iosOnWebContentProcessDidTerminate, - this.iosOnDidReceiveServerRedirectForProvisionalNavigation, - this.initialUrl, - this.initialFile, - this.initialData, - this.initialHeaders, - this.initialOptions, - this.contextMenu - }) { + HeadlessInAppWebView( + {this.onWebViewCreated, + this.onLoadStart, + this.onLoadStop, + this.onLoadError, + this.onLoadHttpError, + this.onProgressChanged, + this.onConsoleMessage, + this.shouldOverrideUrlLoading, + this.onLoadResource, + this.onScrollChanged, + this.onDownloadStart, + this.onLoadResourceCustomScheme, + this.onCreateWindow, + this.onJsAlert, + this.onJsConfirm, + this.onJsPrompt, + this.onReceivedHttpAuthRequest, + this.onReceivedServerTrustAuthRequest, + this.onReceivedClientCertRequest, + this.onFindResultReceived, + this.shouldInterceptAjaxRequest, + this.onAjaxReadyStateChange, + this.onAjaxProgress, + this.shouldInterceptFetchRequest, + this.onUpdateVisitedHistory, + this.onPrint, + this.onLongPressHitTestResult, + this.onEnterFullscreen, + this.onExitFullscreen, + this.onPageCommitVisible, + this.androidOnSafeBrowsingHit, + this.androidOnPermissionRequest, + this.androidOnGeolocationPermissionsShowPrompt, + this.androidOnGeolocationPermissionsHidePrompt, + this.androidShouldInterceptRequest, + this.androidOnRenderProcessGone, + this.androidOnRenderProcessResponsive, + this.androidOnRenderProcessUnresponsive, + this.androidOnFormResubmission, + this.androidOnScaleChanged, + this.iosOnWebContentProcessDidTerminate, + this.iosOnDidReceiveServerRedirectForProvisionalNavigation, + this.initialUrl, + this.initialFile, + this.initialData, + this.initialHeaders, + this.initialOptions, + this.contextMenu}) { uuid = uuidGenerator.v4(); webViewController = new InAppWebViewController(uuid, this); } @@ -89,14 +89,16 @@ class HeadlessInAppWebView implements WebView { _isDisposed = false; Map args = {}; args.putIfAbsent('uuid', () => uuid); - args.putIfAbsent('params', () => { - 'initialUrl': '${Uri.parse(this.initialUrl)}', - 'initialFile': this.initialFile, - 'initialData': this.initialData?.toMap(), - 'initialHeaders': this.initialHeaders, - 'initialOptions': this.initialOptions?.toMap() ?? {}, - 'contextMenu': this.contextMenu?.toMap() ?? {} - }); + args.putIfAbsent( + 'params', + () => { + 'initialUrl': '${Uri.parse(this.initialUrl)}', + 'initialFile': this.initialFile, + 'initialData': this.initialData?.toMap(), + 'initialHeaders': this.initialHeaders, + 'initialOptions': this.initialOptions?.toMap() ?? {}, + 'contextMenu': this.contextMenu?.toMap() ?? {} + }); await _sharedChannel.invokeMethod('createHeadlessWebView', args); } @@ -113,12 +115,12 @@ class HeadlessInAppWebView implements WebView { @override final Future Function(InAppWebViewController controller) - androidOnGeolocationPermissionsHidePrompt; + androidOnGeolocationPermissionsHidePrompt; @override final Future Function( - InAppWebViewController controller, String origin) - androidOnGeolocationPermissionsShowPrompt; + InAppWebViewController controller, String origin) + androidOnGeolocationPermissionsShowPrompt; @override final Future Function( @@ -149,30 +151,31 @@ class HeadlessInAppWebView implements WebView { final String initialUrl; @override - final Future Function(InAppWebViewController controller, String url) onPageCommitVisible; + final Future Function(InAppWebViewController controller, String url) + onPageCommitVisible; @override final Future Function(InAppWebViewController controller) - iosOnDidReceiveServerRedirectForProvisionalNavigation; + iosOnDidReceiveServerRedirectForProvisionalNavigation; @override final Future Function(InAppWebViewController controller) - iosOnWebContentProcessDidTerminate; + iosOnWebContentProcessDidTerminate; @override final Future Function( - InAppWebViewController controller, AjaxRequest ajaxRequest) - onAjaxProgress; + InAppWebViewController controller, AjaxRequest ajaxRequest) + onAjaxProgress; @override final Future Function( - InAppWebViewController controller, AjaxRequest ajaxRequest) - onAjaxReadyStateChange; + InAppWebViewController controller, AjaxRequest ajaxRequest) + onAjaxReadyStateChange; @override final void Function( - InAppWebViewController controller, ConsoleMessage consoleMessage) - onConsoleMessage; + InAppWebViewController controller, ConsoleMessage consoleMessage) + onConsoleMessage; @override final void Function(InAppWebViewController controller, @@ -180,7 +183,7 @@ class HeadlessInAppWebView implements WebView { @override final void Function(InAppWebViewController controller, String url) - onDownloadStart; + onDownloadStart; @override final void Function(InAppWebViewController controller, int activeMatchOrdinal, @@ -208,17 +211,17 @@ class HeadlessInAppWebView implements WebView { @override final void Function( - InAppWebViewController controller, LoadedResource resource) - onLoadResource; + InAppWebViewController controller, LoadedResource resource) + onLoadResource; @override final Future Function( - InAppWebViewController controller, String scheme, String url) - onLoadResourceCustomScheme; + InAppWebViewController controller, String scheme, String url) + onLoadResourceCustomScheme; @override final void Function(InAppWebViewController controller, String url) - onLoadStart; + onLoadStart; @override final void Function(InAppWebViewController controller, String url) onLoadStop; @@ -232,50 +235,50 @@ class HeadlessInAppWebView implements WebView { @override final void Function(InAppWebViewController controller, int progress) - onProgressChanged; + onProgressChanged; @override final Future Function( - InAppWebViewController controller, ClientCertChallenge challenge) - onReceivedClientCertRequest; + InAppWebViewController controller, ClientCertChallenge challenge) + onReceivedClientCertRequest; @override final Future Function( - InAppWebViewController controller, HttpAuthChallenge challenge) - onReceivedHttpAuthRequest; + InAppWebViewController controller, HttpAuthChallenge challenge) + onReceivedHttpAuthRequest; @override final Future Function( - InAppWebViewController controller, ServerTrustChallenge challenge) - onReceivedServerTrustAuthRequest; + InAppWebViewController controller, ServerTrustChallenge challenge) + onReceivedServerTrustAuthRequest; @override final void Function(InAppWebViewController controller, int x, int y) - onScrollChanged; + onScrollChanged; @override final void Function( - InAppWebViewController controller, String url, bool androidIsReload) - onUpdateVisitedHistory; + InAppWebViewController controller, String url, bool androidIsReload) + onUpdateVisitedHistory; @override final void Function(InAppWebViewController controller) onWebViewCreated; @override final Future Function( - InAppWebViewController controller, AjaxRequest ajaxRequest) - shouldInterceptAjaxRequest; + InAppWebViewController controller, AjaxRequest ajaxRequest) + shouldInterceptAjaxRequest; @override final Future Function( - InAppWebViewController controller, FetchRequest fetchRequest) - shouldInterceptFetchRequest; + InAppWebViewController controller, FetchRequest fetchRequest) + shouldInterceptFetchRequest; @override final Future Function( - InAppWebViewController controller, - ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) - shouldOverrideUrlLoading; + InAppWebViewController controller, + ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) + shouldOverrideUrlLoading; @override final void Function(InAppWebViewController controller) onEnterFullscreen; @@ -284,26 +287,31 @@ class HeadlessInAppWebView implements WebView { final void Function(InAppWebViewController controller) onExitFullscreen; @override - final Future Function(InAppWebViewController controller, WebResourceRequest request) - androidShouldInterceptRequest; + final Future Function( + InAppWebViewController controller, WebResourceRequest request) + androidShouldInterceptRequest; @override - final Future Function(InAppWebViewController controller, String url) - androidOnRenderProcessUnresponsive; + final Future Function( + InAppWebViewController controller, String url) + androidOnRenderProcessUnresponsive; @override - final Future Function(InAppWebViewController controller, String url) - androidOnRenderProcessResponsive; + final Future Function( + InAppWebViewController controller, String url) + androidOnRenderProcessResponsive; @override - final Future Function(InAppWebViewController controller, RenderProcessGoneDetail detail) - androidOnRenderProcessGone; + final Future Function( + InAppWebViewController controller, RenderProcessGoneDetail detail) + androidOnRenderProcessGone; @override - final Future Function(InAppWebViewController controller, String url) - androidOnFormResubmission; + final Future Function( + InAppWebViewController controller, String url) androidOnFormResubmission; @override - final Future Function(InAppWebViewController controller, double oldScale, double newScale) - androidOnScaleChanged; -} \ No newline at end of file + final Future Function( + InAppWebViewController controller, double oldScale, double newScale) + androidOnScaleChanged; +} diff --git a/lib/src/http_auth_credentials_database.dart b/lib/src/http_auth_credentials_database.dart index 67ec00d2..2977c2b8 100755 --- a/lib/src/http_auth_credentials_database.dart +++ b/lib/src/http_auth_credentials_database.dart @@ -22,7 +22,7 @@ class HttpAuthCredentialDatabase { static HttpAuthCredentialDatabase _init() { _channel.setMethodCallHandler(_handleMethod); - _instance = new HttpAuthCredentialDatabase(); + _instance = HttpAuthCredentialDatabase(); return _instance; } diff --git a/lib/src/in_app_browser.dart b/lib/src/in_app_browser.dart index 8198ff5d..67912f4e 100755 --- a/lib/src/in_app_browser.dart +++ b/lib/src/in_app_browser.dart @@ -23,7 +23,8 @@ class InAppBrowser { HashMap(); bool _isOpened = false; MethodChannel _channel; - static const MethodChannel _sharedChannel = const MethodChannel('com.pichillilorenzo/flutter_inappbrowser'); + static const MethodChannel _sharedChannel = + const MethodChannel('com.pichillilorenzo/flutter_inappbrowser'); /// WebView Controller that can be used to access the [InAppWebViewController] API. InAppWebViewController webViewController; @@ -35,8 +36,8 @@ class InAppBrowser { MethodChannel('com.pichillilorenzo/flutter_inappbrowser_$uuid'); this._channel.setMethodCallHandler(handleMethod); _isOpened = false; - webViewController = new InAppWebViewController.fromInAppBrowser( - uuid, this._channel, this); + webViewController = + new InAppWebViewController.fromInAppBrowser(uuid, this._channel, this); } Future handleMethod(MethodCall call) async { @@ -117,8 +118,6 @@ class InAppBrowser { assert(assetFilePath != null && assetFilePath.isNotEmpty); this.throwIsAlreadyOpened(message: 'Cannot open $assetFilePath!'); - - Map args = {}; args.putIfAbsent('uuid', () => uuid); args.putIfAbsent('url', () => assetFilePath); @@ -217,20 +216,19 @@ class InAppBrowser { options = options.cast(); inAppBrowserClassOptions.crossPlatform = InAppBrowserOptions.fromMap(options); - inAppBrowserClassOptions.inAppWebViewGroupOptions = InAppWebViewGroupOptions(); + inAppBrowserClassOptions.inAppWebViewGroupOptions = + InAppWebViewGroupOptions(); inAppBrowserClassOptions.inAppWebViewGroupOptions.crossPlatform = InAppWebViewOptions.fromMap(options); if (Platform.isAndroid) { inAppBrowserClassOptions.android = AndroidInAppBrowserOptions.fromMap(options); - inAppBrowserClassOptions - .inAppWebViewGroupOptions.android = + inAppBrowserClassOptions.inAppWebViewGroupOptions.android = AndroidInAppWebViewOptions.fromMap(options); } else if (Platform.isIOS) { - inAppBrowserClassOptions.ios = - IOSInAppBrowserOptions.fromMap(options); - inAppBrowserClassOptions.inAppWebViewGroupOptions - .ios = IOSInAppWebViewOptions.fromMap(options); + inAppBrowserClassOptions.ios = IOSInAppBrowserOptions.fromMap(options); + inAppBrowserClassOptions.inAppWebViewGroupOptions.ios = + IOSInAppWebViewOptions.fromMap(options); } } @@ -305,7 +303,8 @@ class InAppBrowser { ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView,%20java.lang.String) ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455641-webview // ignore: missing_return - Future shouldOverrideUrlLoading(ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) {} + Future shouldOverrideUrlLoading( + ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) {} ///Event fired when the [InAppBrowser] webview loads a resource. /// @@ -555,8 +554,8 @@ class InAppBrowser { /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String,%20android.webkit.GeolocationPermissions.Callback) Future - // ignore: missing_return - androidOnGeolocationPermissionsShowPrompt(String origin) {} + // ignore: missing_return + androidOnGeolocationPermissionsShowPrompt(String origin) {} ///Notify the host application that a request for Geolocation permissions, made with a previous call to [androidOnGeolocationPermissionsShowPrompt] has been canceled. ///Any related UI should therefore be hidden. @@ -584,8 +583,8 @@ class InAppBrowser { ///- https://developer.android.com/reference/android/webkit/WebViewClient#shouldInterceptRequest(android.webkit.WebView,%20android.webkit.WebResourceRequest) ///- https://developer.android.com/reference/android/webkit/WebViewClient#shouldInterceptRequest(android.webkit.WebView,%20java.lang.String) Future - // ignore: missing_return - androidShouldInterceptRequest(WebResourceRequest request) {} + // ignore: missing_return + androidShouldInterceptRequest(WebResourceRequest request) {} ///Event called when the renderer currently associated with the WebView becomes unresponsive as a result of a long running blocking task such as the execution of JavaScript. /// @@ -606,8 +605,8 @@ class InAppBrowser { /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessUnresponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess) Future - // ignore: missing_return - androidOnRenderProcessUnresponsive(String url) {} + // ignore: missing_return + androidOnRenderProcessUnresponsive(String url) {} ///Event called once when an unresponsive renderer currently associated with the WebView becomes responsive. /// @@ -621,8 +620,8 @@ class InAppBrowser { /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessResponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess) Future - // ignore: missing_return - androidOnRenderProcessResponsive(String url) {} + // ignore: missing_return + androidOnRenderProcessResponsive(String url) {} ///Event fired when the given WebView's render process has exited. ///The application's implementation of this callback should only attempt to clean up the WebView. @@ -641,8 +640,8 @@ class InAppBrowser { /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onFormResubmission(android.webkit.WebView,%20android.os.Message,%20android.os.Message) Future - // ignore: missing_return - androidOnFormResubmission(String url) {} + // ignore: missing_return + androidOnFormResubmission(String url) {} ///Event fired when the scale applied to the WebView has changed. /// diff --git a/lib/src/in_app_localhost_server.dart b/lib/src/in_app_localhost_server.dart index 273fcd2b..70634eeb 100755 --- a/lib/src/in_app_localhost_server.dart +++ b/lib/src/in_app_localhost_server.dart @@ -29,7 +29,7 @@ class InAppLocalhostServer { throw Exception('Server already started on http://localhost:$_port'); } - var completer = new Completer(); + var completer = Completer(); runZoned(() { HttpServer.bind('127.0.0.1', _port).then((server) { @@ -62,7 +62,7 @@ class InAppLocalhostServer { } request.response.headers.contentType = - new ContentType(contentType[0], contentType[1], charset: 'utf-8'); + ContentType(contentType[0], contentType[1], charset: 'utf-8'); request.response.add(body); request.response.close(); }); diff --git a/lib/src/in_app_webview.dart b/lib/src/in_app_webview.dart index 0d8d0f9c..59645a2f 100755 --- a/lib/src/in_app_webview.dart +++ b/lib/src/in_app_webview.dart @@ -116,7 +116,8 @@ class InAppWebView extends StatefulWidget implements WebView { final ContextMenu contextMenu; @override - final Future Function(InAppWebViewController controller, String url) onPageCommitVisible; + final Future Function(InAppWebViewController controller, String url) + onPageCommitVisible; @override final Future Function(InAppWebViewController controller) @@ -251,28 +252,33 @@ class InAppWebView extends StatefulWidget implements WebView { final void Function(InAppWebViewController controller) onExitFullscreen; @override - final Future Function(InAppWebViewController controller, WebResourceRequest request) - androidShouldInterceptRequest; + final Future Function( + InAppWebViewController controller, WebResourceRequest request) + androidShouldInterceptRequest; @override - final Future Function(InAppWebViewController controller, String url) - androidOnRenderProcessUnresponsive; + final Future Function( + InAppWebViewController controller, String url) + androidOnRenderProcessUnresponsive; @override - final Future Function(InAppWebViewController controller, String url) - androidOnRenderProcessResponsive; + final Future Function( + InAppWebViewController controller, String url) + androidOnRenderProcessResponsive; @override - final Future Function(InAppWebViewController controller, RenderProcessGoneDetail detail) - androidOnRenderProcessGone; + final Future Function( + InAppWebViewController controller, RenderProcessGoneDetail detail) + androidOnRenderProcessGone; @override - final Future Function(InAppWebViewController controller, String url) - androidOnFormResubmission; + final Future Function( + InAppWebViewController controller, String url) androidOnFormResubmission; @override - final Future Function(InAppWebViewController controller, double oldScale, double newScale) - androidOnScaleChanged; + final Future Function( + InAppWebViewController controller, double oldScale, double newScale) + androidOnScaleChanged; } class _InAppWebViewState extends State { diff --git a/lib/src/in_app_webview_controller.dart b/lib/src/in_app_webview_controller.dart index 722791c6..2b93031d 100644 --- a/lib/src/in_app_webview_controller.dart +++ b/lib/src/in_app_webview_controller.dart @@ -1590,7 +1590,8 @@ class AndroidInAppWebViewController { ///If `true`, [basename] is assumed to be a directory in which a filename will be chosen according to the URL of the current page. /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#saveWebArchive(java.lang.String,%20boolean,%20android.webkit.ValueCallback%3Cjava.lang.String%3E) - Future saveWebArchive({@required String basename, @required bool autoname}) async { + Future saveWebArchive( + {@required String basename, @required bool autoname}) async { assert(basename != null && autoname != null); Map args = {}; args.putIfAbsent("basename", () => basename); @@ -1681,7 +1682,10 @@ class AndroidInAppWebViewController { ///**Official Android API**: https://developer.android.com/reference/androidx/webkit/WebViewCompat#getCurrentWebViewPackage(android.content.Context) static Future getCurrentWebViewPackage() async { Map args = {}; - Map packageInfo = (await InAppWebViewController._staticChannel.invokeMethod('getCurrentWebViewPackage', args))?.cast(); + Map packageInfo = (await InAppWebViewController + ._staticChannel + .invokeMethod('getCurrentWebViewPackage', args)) + ?.cast(); return AndroidWebViewPackageInfo.fromMap(packageInfo); } } diff --git a/lib/src/types.dart b/lib/src/types.dart index bc333b78..ce4ee999 100755 --- a/lib/src/types.dart +++ b/lib/src/types.dart @@ -87,6 +87,24 @@ class LoadedResource { double duration; LoadedResource({this.initiatorType, this.url, this.startTime, this.duration}); + + Map toMap() { + return { + "initiatorType": initiatorType, + "url": url, + "startTime": startTime, + "duration": duration + }; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Initial [data] as a content for an [WebView] instance, using [baseUrl] as the base URL for it. @@ -122,6 +140,15 @@ class InAppWebViewInitialData { "historyUrl": historyUrl }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class representing a resource request of the WebView used by the event [WebView.androidShouldInterceptRequest]. @@ -131,14 +158,17 @@ class InAppWebViewInitialData { class WebResourceRequest { ///The URL for which the resource request was made. String url; + ///The headers associated with the request. /// ///**NOTE**: Available on Android 21+. For Android < 21 it will be always `null`. Map headers; + ///The method associated with the request, for example `GET`. /// ///**NOTE**: Available on Android 21+. For Android < 21 it will be always "GET". String method; + ///Gets whether a gesture (such as a click) was associated with the request. ///For security reasons in certain situations this method may return `false` even though ///the sequence of events which caused the request to be created was initiated by a user @@ -146,23 +176,44 @@ class WebResourceRequest { /// ///**NOTE**: Available on Android 21+. For Android < 21 it will be always `false`. bool hasGesture; + ///Whether the request was made in order to fetch the main frame's document. /// ///**NOTE**: Available on Android 21+. For Android < 21 it will be always `true`. bool isForMainFrame; + ///Whether the request was a result of a server-side redirect. /// ///**NOTE**: Available on Android 21+. For Android < 21 it will be always `false`. bool isRedirect; - WebResourceRequest({ - @required this.url, - this.headers, - this.method, - this.hasGesture, - this.isForMainFrame, - this.isRedirect - }); + WebResourceRequest( + {@required this.url, + this.headers, + this.method, + this.hasGesture, + this.isForMainFrame, + this.isRedirect}); + + Map toMap() { + return { + "url": url, + "headers": headers, + "method": method, + "hasGesture": hasGesture, + "isForMainFrame": isForMainFrame, + "isRedirect": isRedirect + }; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class representing a resource response of the WebView used by the event [WebView.androidShouldInterceptRequest]. @@ -172,33 +223,37 @@ class WebResourceRequest { class WebResourceResponse { ///The resource response's MIME type, for example `text/html`. String contentType; + ///The resource response's encoding. The default value is `utf-8`. String contentEncoding; + ///The data provided by the resource response. Uint8List data; + ///The headers for the resource response. If [headers] isn't `null`, then you need to set also [statusCode] and [reasonPhrase]. /// ///**NOTE**: Available on Android 21+. For Android < 21 it won't be used. Map headers; + ///The status code needs to be in the ranges [100, 299], [400, 599]. Causing a redirect by specifying a 3xx code is not supported. ///If statusCode is set, then you need to set also [headers] and [reasonPhrase]. This value cannot be `null`. /// ///**NOTE**: Available on Android 21+. For Android < 21 it won't be used. int statusCode; + ///The phrase describing the status code, for example `"OK"`. Must be non-empty. ///If reasonPhrase is set, then you need to set also [headers] and [reasonPhrase]. This value cannot be `null`. /// ///**NOTE**: Available on Android 21+. For Android < 21 it won't be used. String reasonPhrase; - WebResourceResponse({ - this.contentType = "", - this.contentEncoding = "utf-8", - this.data = null, - this.headers, - this.statusCode, - this.reasonPhrase - }); + WebResourceResponse( + {this.contentType = "", + this.contentEncoding = "utf-8", + this.data = null, + this.headers, + this.statusCode, + this.reasonPhrase}); Map toMap() { return { @@ -209,6 +264,15 @@ class WebResourceResponse { "reasonPhrase": reasonPhrase }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class representing the response returned by the [WebView.onLoadResourceCustomScheme] event. @@ -228,13 +292,22 @@ class CustomSchemeResponse { @required this.contentType, this.contentEnconding = 'utf-8'}); - Map toJson() { + Map toMap() { return { 'content-type': contentType, 'content-encoding': contentEnconding, 'data': data }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class representing a JavaScript console message from WebCore. @@ -247,6 +320,19 @@ class ConsoleMessage { ConsoleMessage( {this.message = "", this.messageLevel = ConsoleMessageLevel.LOG}); + + Map toMap() { + return {"message": message, "messageLevel": messageLevel?.toValue()}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///This class contains a snapshot of the current back/forward list for a [WebView]. @@ -258,6 +344,19 @@ class WebHistory { int currentIndex; WebHistory({this.list, this.currentIndex}); + + Map toMap() { + return {"list": list, "currentIndex": currentIndex}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///A convenience class for accessing fields in an entry in the back/forward list of a WebView. Each [WebHistoryItem] is a snapshot of the requested history item. @@ -279,6 +378,25 @@ class WebHistoryItem { WebHistoryItem( {this.originalUrl, this.title, this.url, this.index, this.offset}); + + Map toMap() { + return { + "originalUrl": originalUrl, + "title": title, + "url": url, + "index": index, + "offset": offset + }; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by the host application to set the Geolocation permission state for an origin during the [WebView.androidOnGeolocationPermissionsShowPrompt] event. @@ -298,6 +416,15 @@ class GeolocationPermissionShowPromptResponse { Map toMap() { return {"origin": origin, "allow": allow, "retain": retain}; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [JsAlertResponse] class. @@ -344,6 +471,15 @@ class JsAlertResponse { "action": action?.toValue() }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [JsConfirmResponse] class. @@ -396,6 +532,15 @@ class JsConfirmResponse { "action": action?.toValue() }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [JsPromptResponse] class. @@ -458,6 +603,15 @@ class JsPromptResponse { "action": action?.toValue() }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the reason the resource was caught by Safe Browsing. @@ -547,6 +701,15 @@ class SafeBrowsingResponse { Map toMap() { return {"report": report, "action": action?.toValue()}; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [HttpAuthResponse] class. @@ -601,6 +764,15 @@ class HttpAuthResponse { "action": action?.toValue() }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the challenge of the [WebView.onReceivedHttpAuthRequest] event. @@ -615,6 +787,22 @@ class HttpAuthChallenge { HttpAuthChallenge( {@required this.previousFailureCount, @required this.protectionSpace}) : assert(previousFailureCount != null && protectionSpace != null); + + Map toMap() { + return { + "previousFailureCount": previousFailureCount, + "protectionSpace": protectionSpace?.toMap() + }; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents a protection space requiring authentication. @@ -636,6 +824,19 @@ class ProtectionSpace { ProtectionSpace( {@required this.host, @required this.protocol, this.realm, this.port}) : assert(host != null && protocol != null); + + Map toMap() { + return {"host": host, "protocol": protocol, "realm": realm, "port": port}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the credentials of an http authentication. @@ -649,6 +850,19 @@ class HttpAuthCredential { HttpAuthCredential({@required this.username, @required this.password}) : assert(username != null && password != null); + + Map toMap() { + return {"username": username, "password": password}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [ServerTrustAuthResponse] class. @@ -681,6 +895,15 @@ class ServerTrustAuthResponse { Map toMap() { return {"action": action?.toValue()}; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the challenge of the [WebView.onReceivedServerTrustAuthRequest] event. @@ -708,6 +931,24 @@ class ServerTrustChallenge { this.message, this.serverCertificate}) : assert(protectionSpace != null && error != null); + + Map toMap() { + return { + "protectionSpace": protectionSpace?.toMap(), + "error": error, + "message": message, + "serverCertificate": serverCertificate + }; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [ClientCertResponse] class. @@ -764,6 +1005,15 @@ class ClientCertResponse { "action": action?.toValue() }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the challenge of the [WebView.onReceivedClientCertRequest] event. @@ -774,6 +1024,19 @@ class ClientCertChallenge { ClientCertChallenge({@required this.protectionSpace}) : assert(protectionSpace != null); + + Map toMap() { + return {"protectionSpace": protectionSpace?.toMap()}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents a favicon of a website. It is used by [InAppWebViewController.getFavicons] method. @@ -793,8 +1056,17 @@ class Favicon { Favicon({@required this.url, this.rel, this.width, this.height}) : assert(url != null); + Map toMap() { + return {"url": url, "rel": rel, "width": width, "height": height}; + } + + Map toJson() { + return this.toMap(); + } + + @override String toString() { - return "url: $url, rel: $rel, width: $width, height: $height"; + return toMap().toString(); } } @@ -949,7 +1221,7 @@ class AndroidLayoutAlgorithm { const AndroidLayoutAlgorithm._internal(this._value); static AndroidLayoutAlgorithm fromValue(String value) { - return (["NORMAL", "TEXT_AUTOSIZING"].contains(value)) + return (["NORMAL", "TEXT_AUTOSIZING", "NARROW_COLUMNS"].contains(value)) ? AndroidLayoutAlgorithm._internal(value) : null; } @@ -969,6 +1241,10 @@ class AndroidLayoutAlgorithm { static const TEXT_AUTOSIZING = const AndroidLayoutAlgorithm._internal("TEXT_AUTOSIZING"); + ///NARROW_COLUMNS makes all columns no wider than the screen if possible. Only use this for API levels prior to `Build.VERSION_CODES.KITKAT`. + static const NARROW_COLUMNS = + const AndroidLayoutAlgorithm._internal("NARROW_COLUMNS"); + bool operator ==(value) => value == _value; @override @@ -1414,6 +1690,11 @@ class InAppWebViewGroupOptions { Map toJson() { return this.toMap(); } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the options that can be used for an [InAppBrowser] WebView. @@ -1455,6 +1736,11 @@ class InAppBrowserClassOptions { Map toJson() { return this.toMap(); } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the options that can be used for an [ChromeSafariBrowser] window. @@ -1479,6 +1765,11 @@ class ChromeSafariBrowserClassOptions { Map toJson() { return this.toMap(); } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [AjaxRequest] class. @@ -1509,6 +1800,11 @@ class AjaxRequestAction { Map toJson() { return this.toMap(); } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [AjaxRequestEvent] class. @@ -1770,6 +2066,11 @@ class AjaxRequest { Map toJson() { return this.toMap(); } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [FetchRequest] class. @@ -1802,6 +2103,15 @@ class FetchRequestCredential { Map toMap() { return {"type": type}; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the default credentials used by an [FetchRequest]. @@ -1817,6 +2127,15 @@ class FetchRequestCredentialDefault extends FetchRequestCredential { "value": value, }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents a [FederatedCredential](https://developer.mozilla.org/en-US/docs/Web/API/FederatedCredential) type of credentials. @@ -1850,6 +2169,15 @@ class FetchRequestFederatedCredential extends FetchRequestCredential { "iconURL": iconURL }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents a [PasswordCredential](https://developer.mozilla.org/en-US/docs/Web/API/PasswordCredential) type of credentials. @@ -1879,6 +2207,15 @@ class FetchRequestPasswordCredential extends FetchRequestCredential { "iconURL": iconURL }; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents a HTTP request created with JavaScript using the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). @@ -1959,6 +2296,11 @@ class FetchRequest { return this.toMap(); } + @override + String toString() { + return toMap().toString(); + } + static FetchRequestCredential createFetchRequestCredentialFromMap( credentialsMap) { if (credentialsMap != null) { @@ -2111,6 +2453,19 @@ class Cookie { dynamic value; Cookie({@required this.name, @required this.value}); + + Map toMap() { + return {"name": name, "value": value}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [PermissionRequestResponse] class. @@ -2148,6 +2503,15 @@ class PermissionRequestResponse { Map toMap() { return {"resources": resources, "action": action?.toValue()}; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that is used by [WebView.shouldOverrideUrlLoading] event. @@ -2251,6 +2615,27 @@ class ShouldOverrideUrlLoadingRequest { this.androidHasGesture, this.androidIsRedirect, this.iosWKNavigationType}); + + Map toMap() { + return { + "url": url, + "headers": headers, + "method": method, + "isForMainFrame": isForMainFrame, + "androidHasGesture": androidHasGesture, + "androidIsRedirect": androidIsRedirect, + "iosWKNavigationType": iosWKNavigationType?.toValue() + }; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the navigation request used by the [WebView.onCreateWindow] event. @@ -2272,6 +2657,24 @@ class OnCreateWindowRequest { this.androidIsDialog, this.androidIsUserGesture, this.iosWKNavigationType}); + + Map toMap() { + return { + "url": url, + "androidIsDialog": androidIsDialog, + "androidIsUserGesture": androidIsUserGesture, + "iosWKNavigationType": iosWKNavigationType?.toValue() + }; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that encapsulates information about the amount of storage currently used by an origin for the JavaScript storage APIs. @@ -2292,6 +2695,11 @@ class AndroidWebStorageOrigin { return {"origin": origin, "quota": quota, "usage": usage}; } + Map toJson() { + return this.toMap(); + } + + @override String toString() { return toMap().toString(); } @@ -2415,6 +2823,11 @@ class IOSWKWebsiteDataRecord { return {"displayName": displayName, "dataTypes": dataTypesString}; } + Map toJson() { + return this.toMap(); + } + + @override String toString() { return toMap().toString(); } @@ -2499,6 +2912,19 @@ class InAppWebViewHitTestResult { String extra; InAppWebViewHitTestResult({this.type, this.extra}); + + Map toMap() { + return {"type": type?.toValue(), "extra": extra}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class that represents the action to take used by the [WebView.androidOnRenderProcessUnresponsive] and [WebView.androidOnRenderProcessResponsive] event @@ -2519,9 +2945,7 @@ class WebViewRenderProcessAction { int get hashCode => _value.hashCode; Map toMap() { - return { - "action": _value - }; + return {"action": _value}; } } @@ -2532,11 +2956,28 @@ class RenderProcessGoneDetail { /// ///If the render process was killed, this is most likely caused by the system being low on memory. bool didCrash; + /// Returns the renderer priority that was set at the time that the renderer exited. This may be greater than the priority that /// any individual [WebView] requested using []. RendererPriority rendererPriorityAtExit; RenderProcessGoneDetail({this.didCrash, this.rendererPriorityAtExit}); + + Map toMap() { + return { + "didCrash": didCrash, + "rendererPriorityAtExit": rendererPriorityAtExit?.toValue() + }; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///Class used by [RendererPriorityPolicy] class. @@ -2574,7 +3015,8 @@ class RendererPriority { static const RENDERER_PRIORITY_BOUND = const RendererPriority._internal(1); ///The renderer associated with this WebView is bound with Android `Context#BIND_IMPORTANT`. - static const RENDERER_PRIORITY_IMPORTANT = const RendererPriority._internal(2); + static const RENDERER_PRIORITY_IMPORTANT = + const RendererPriority._internal(2); bool operator ==(value) => value == _value; @@ -2591,10 +3033,13 @@ class RendererPriority { class RendererPriorityPolicy { ///The minimum priority at which this WebView desires the renderer process to be bound. RendererPriority rendererRequestedPriority; + ///If true, this flag specifies that when this WebView is not visible, it will be treated as if it had requested a priority of [RendererPriority.RENDERER_PRIORITY_WAIVED]. bool waivedWhenNotVisible; - RendererPriorityPolicy({@required this.rendererRequestedPriority, @required this.waivedWhenNotVisible}); + RendererPriorityPolicy( + {@required this.rendererRequestedPriority, + @required this.waivedWhenNotVisible}); Map toMap() { return { @@ -2603,11 +3048,22 @@ class RendererPriorityPolicy { }; } + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } + static RendererPriorityPolicy fromMap(Map map) { - return map != null ? RendererPriorityPolicy( - rendererRequestedPriority: RendererPriority.fromValue(map["rendererRequestedPriority"]), - waivedWhenNotVisible: map["waivedWhenNotVisible"] - ) : RendererPriorityPolicy(); + return map != null + ? RendererPriorityPolicy( + rendererRequestedPriority: + RendererPriority.fromValue(map["rendererRequestedPriority"]), + waivedWhenNotVisible: map["waivedWhenNotVisible"]) + : RendererPriorityPolicy(); } } @@ -2631,9 +3087,16 @@ class FormResubmissionAction { int get hashCode => _value.hashCode; Map toMap() { - return { - "action": _value - }; + return {"action": _value}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); } } @@ -2666,16 +3129,14 @@ class AndroidOverScrollMode { } ///Always allow a user to over-scroll this view, provided it is a view that can scroll. - static const OVER_SCROLL_ALWAYS = - const AndroidOverScrollMode._internal(0); + static const OVER_SCROLL_ALWAYS = const AndroidOverScrollMode._internal(0); ///Allow a user to over-scroll this view only if the content is large enough to meaningfully scroll, provided it is a view that can scroll. static const OVER_SCROLL_IF_CONTENT_SCROLLS = - const AndroidOverScrollMode._internal(1); + const AndroidOverScrollMode._internal(1); ///Never allow a user to over-scroll this view. - static const OVER_SCROLL_NEVER = - const AndroidOverScrollMode._internal(2); + static const OVER_SCROLL_NEVER = const AndroidOverScrollMode._internal(2); bool operator ==(value) => value == _value; @@ -2721,22 +3182,22 @@ class AndroidScrollBarStyle { ///The scrollbar style to display the scrollbars inside the content area, without increasing the padding. ///The scrollbars will be overlaid with translucency on the view's content. static const SCROLLBARS_INSIDE_OVERLAY = - const AndroidScrollBarStyle._internal(0); + const AndroidScrollBarStyle._internal(0); ///The scrollbar style to display the scrollbars inside the padded area, increasing the padding of the view. ///The scrollbars will not overlap the content area of the view. static const SCROLLBARS_INSIDE_INSET = - const AndroidScrollBarStyle._internal(16777216); + const AndroidScrollBarStyle._internal(16777216); ///The scrollbar style to display the scrollbars at the edge of the view, without increasing the padding. ///The scrollbars will be overlaid with translucency. static const SCROLLBARS_OUTSIDE_OVERLAY = - const AndroidScrollBarStyle._internal(33554432); + const AndroidScrollBarStyle._internal(33554432); ///The scrollbar style to display the scrollbars at the edge of the view, increasing the padding of the view. ///The scrollbars will only overlap the background, if any. static const SCROLLBARS_OUTSIDE_INSET = - const AndroidScrollBarStyle._internal(50331648); + const AndroidScrollBarStyle._internal(50331648); bool operator ==(value) => value == _value; @@ -2773,15 +3234,15 @@ class AndroidVerticalScrollbarPosition { ///Position the scroll bar at the default position as determined by the system. static const SCROLLBAR_POSITION_DEFAULT = - const AndroidVerticalScrollbarPosition._internal(0); + const AndroidVerticalScrollbarPosition._internal(0); ///Position the scroll bar along the left edge. static const SCROLLBAR_POSITION_LEFT = - const AndroidVerticalScrollbarPosition._internal(1); + const AndroidVerticalScrollbarPosition._internal(1); ///Position the scroll bar along the right edge. static const SCROLLBAR_POSITION_RIGHT = - const AndroidVerticalScrollbarPosition._internal(2); + const AndroidVerticalScrollbarPosition._internal(2); bool operator ==(value) => value == _value; @@ -2793,15 +3254,29 @@ class AndroidVerticalScrollbarPosition { class AndroidWebViewPackageInfo { ///The version name of this WebView package. String versionName; + ///The name of this WebView package. String packageName; AndroidWebViewPackageInfo({this.versionName, this.packageName}); static AndroidWebViewPackageInfo fromMap(Map map) { - return map != null ? AndroidWebViewPackageInfo( - versionName: map["versionName"], - packageName: map["packageName"] - ) : AndroidWebViewPackageInfo(); + return map != null + ? AndroidWebViewPackageInfo( + versionName: map["versionName"], packageName: map["packageName"]) + : AndroidWebViewPackageInfo(); + } + + Map toMap() { + return {"versionName": versionName, "packageName": packageName}; + } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); } } diff --git a/lib/src/web_storage_manager.dart b/lib/src/web_storage_manager.dart index 945579e9..df198eeb 100755 --- a/lib/src/web_storage_manager.dart +++ b/lib/src/web_storage_manager.dart @@ -40,10 +40,15 @@ class AndroidWebStorageManager { List originsList = []; Map args = {}; - List> origins = (await WebStorageManager._channel.invokeMethod('getOrigins', args)).cast>(); + List> origins = + (await WebStorageManager._channel.invokeMethod('getOrigins', args)) + .cast>(); - for(var origin in origins) { - originsList.add(AndroidWebStorageOrigin(origin: origin["origin"], quota: origin["quota"], usage: origin["usage"])); + for (var origin in origins) { + originsList.add(AndroidWebStorageOrigin( + origin: origin["origin"], + quota: origin["quota"], + usage: origin["usage"])); } return originsList; @@ -72,7 +77,8 @@ class AndroidWebStorageManager { assert(origin != null); Map args = {}; args.putIfAbsent("origin", () => origin); - return await WebStorageManager._channel.invokeMethod('getQuotaForOrigin', args); + return await WebStorageManager._channel + .invokeMethod('getQuotaForOrigin', args); } ///Gets the amount of storage currently being used by both the Application Cache and Web SQL Database APIs by the given [origin]. @@ -81,7 +87,8 @@ class AndroidWebStorageManager { assert(origin != null); Map args = {}; args.putIfAbsent("origin", () => origin); - return await WebStorageManager._channel.invokeMethod('getUsageForOrigin', args); + return await WebStorageManager._channel + .invokeMethod('getUsageForOrigin', args); } } @@ -93,7 +100,8 @@ class IOSWebStorageManager { ///Fetches data records containing the given website data types. /// ///[dataTypes] represents the website data types to fetch records for. - Future> fetchDataRecords({@required Set dataTypes}) async { + Future> fetchDataRecords( + {@required Set dataTypes}) async { assert(dataTypes != null); List recordList = []; List dataTypesList = []; @@ -102,14 +110,17 @@ class IOSWebStorageManager { } Map args = {}; args.putIfAbsent("dataTypes", () => dataTypesList); - List> records = (await WebStorageManager._channel.invokeMethod('fetchDataRecords', args)).cast>(); - for(var record in records) { + List> records = (await WebStorageManager._channel + .invokeMethod('fetchDataRecords', args)) + .cast>(); + for (var record in records) { List dataTypesString = record["dataTypes"].cast(); Set dataTypes = Set(); - for(var dataType in dataTypesString) { + for (var dataType in dataTypesString) { dataTypes.add(IOSWKWebsiteDataType.fromValue(dataType)); } - recordList.add(IOSWKWebsiteDataRecord(displayName: record["displayName"], dataTypes: dataTypes)); + recordList.add(IOSWKWebsiteDataRecord( + displayName: record["displayName"], dataTypes: dataTypes)); } return recordList; } @@ -119,7 +130,9 @@ class IOSWebStorageManager { ///[dataTypes] represents the website data types that should be removed. /// ///[dataRecords] represents the website data records to delete website data for. - Future removeDataFor({@required Set dataTypes, @required List dataRecords}) async { + Future removeDataFor( + {@required Set dataTypes, + @required List dataRecords}) async { assert(dataTypes != null && dataRecords != null); List dataTypesList = []; @@ -143,7 +156,9 @@ class IOSWebStorageManager { ///[dataTypes] represents the website data types that should be removed. /// ///[date] represents a date. All website data modified after this date will be removed. - Future removeDataModifiedSince({@required Set dataTypes, @required DateTime date}) async { + Future removeDataModifiedSince( + {@required Set dataTypes, + @required DateTime date}) async { assert(dataTypes != null && date != null); List dataTypesList = []; @@ -156,6 +171,7 @@ class IOSWebStorageManager { Map args = {}; args.putIfAbsent("dataTypes", () => dataTypesList); args.putIfAbsent("timestamp", () => timestamp); - await WebStorageManager._channel.invokeMethod('removeDataModifiedSince', args); + await WebStorageManager._channel + .invokeMethod('removeDataModifiedSince', args); } } diff --git a/lib/src/webview.dart b/lib/src/webview.dart index 2e082a26..135469a2 100644 --- a/lib/src/webview.dart +++ b/lib/src/webview.dart @@ -15,7 +15,7 @@ abstract class WebView { ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap) ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455621-webview final void Function(InAppWebViewController controller, String url) - onLoadStart; + onLoadStart; ///Event fired when the [WebView] finishes loading an [url]. /// @@ -49,14 +49,14 @@ abstract class WebView { /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onProgressChanged(android.webkit.WebView,%20int) final void Function(InAppWebViewController controller, int progress) - onProgressChanged; + onProgressChanged; ///Event fired when the [WebView] receives a [ConsoleMessage]. /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onConsoleMessage(android.webkit.ConsoleMessage) final void Function( - InAppWebViewController controller, ConsoleMessage consoleMessage) - onConsoleMessage; + InAppWebViewController controller, ConsoleMessage consoleMessage) + onConsoleMessage; ///Give the host application a chance to take control when a URL is about to be loaded in the current WebView. This event is not called on the initial load of the WebView. /// @@ -73,16 +73,16 @@ abstract class WebView { ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView,%20java.lang.String) ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455641-webview final Future Function( - InAppWebViewController controller, - ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) - shouldOverrideUrlLoading; + InAppWebViewController controller, + ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) + shouldOverrideUrlLoading; ///Event fired when the [WebView] loads a resource. /// ///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useOnLoadResource] and [InAppWebViewOptions.javaScriptEnabled] options to `true`. final void Function( - InAppWebViewController controller, LoadedResource resource) - onLoadResource; + InAppWebViewController controller, LoadedResource resource) + onLoadResource; ///Event fired when the [WebView] scrolls. /// @@ -93,7 +93,7 @@ abstract class WebView { ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#onScrollChanged(int,%20int,%20int,%20int) ///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619392-scrollviewdidscroll final void Function(InAppWebViewController controller, int x, int y) - onScrollChanged; + onScrollChanged; ///Event fired when [WebView] recognizes a downloadable file. ///To download the file, you can use the [flutter_downloader](https://pub.dev/packages/flutter_downloader) plugin. @@ -105,7 +105,7 @@ abstract class WebView { ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#setDownloadListener(android.webkit.DownloadListener) ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview final void Function(InAppWebViewController controller, String url) - onDownloadStart; + onDownloadStart; ///Event fired when the [WebView] finds the `custom-scheme` while loading a resource. Here you can handle the url request and return a [CustomSchemeResponse] to load a specific resource encoded to `base64`. /// @@ -115,8 +115,8 @@ abstract class WebView { /// ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkurlschemehandler final Future Function( - InAppWebViewController controller, String scheme, String url) - onLoadResourceCustomScheme; + InAppWebViewController controller, String scheme, String url) + onLoadResourceCustomScheme; ///Event fired when the [WebView] requests the host application to create a new window, ///for example when trying to open a link with `target="_blank"` or when `window.open()` is called by JavaScript side. @@ -169,8 +169,8 @@ abstract class WebView { ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedHttpAuthRequest(android.webkit.WebView,%20android.webkit.HttpAuthHandler,%20java.lang.String,%20java.lang.String) ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview final Future Function( - InAppWebViewController controller, HttpAuthChallenge challenge) - onReceivedHttpAuthRequest; + InAppWebViewController controller, HttpAuthChallenge challenge) + onReceivedHttpAuthRequest; ///Event fired when the WebView need to perform server trust authentication (certificate validation). ///The host application must return either [ServerTrustAuthResponse] instance with [ServerTrustAuthResponseAction.CANCEL] or [ServerTrustAuthResponseAction.PROCEED]. @@ -180,8 +180,8 @@ abstract class WebView { ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedSslError(android.webkit.WebView,%20android.webkit.SslErrorHandler,%20android.net.http.SslError) ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview final Future Function( - InAppWebViewController controller, ServerTrustChallenge challenge) - onReceivedServerTrustAuthRequest; + InAppWebViewController controller, ServerTrustChallenge challenge) + onReceivedServerTrustAuthRequest; ///Notify the host application to handle an SSL client certificate request. ///Webview stores the response in memory (for the life of the application) if [ClientCertResponseAction.PROCEED] or [ClientCertResponseAction.CANCEL] @@ -193,8 +193,8 @@ abstract class WebView { ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedClientCertRequest(android.webkit.WebView,%20android.webkit.ClientCertRequest) ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview final Future Function( - InAppWebViewController controller, ClientCertChallenge challenge) - onReceivedClientCertRequest; + InAppWebViewController controller, ClientCertChallenge challenge) + onReceivedClientCertRequest; ///Event fired as find-on-page operations progress. ///The listener may be notified multiple times while the operation is underway, and the numberOfMatches value should not be considered final unless [isDoneCounting] is true. @@ -220,8 +220,8 @@ abstract class WebView { ///used to intercept ajax requests is loaded as soon as possible so it won't be instantaneous as iOS but just after some milliseconds (< ~100ms). ///Inside the `window.addEventListener("flutterInAppWebViewPlatformReady")` event, the ajax requests will be intercept for sure. final Future Function( - InAppWebViewController controller, AjaxRequest ajaxRequest) - shouldInterceptAjaxRequest; + InAppWebViewController controller, AjaxRequest ajaxRequest) + shouldInterceptAjaxRequest; ///Event fired whenever the `readyState` attribute of an `XMLHttpRequest` changes. ///It gives the host application a chance to abort the request. @@ -234,8 +234,8 @@ abstract class WebView { ///used to intercept ajax requests is loaded as soon as possible so it won't be instantaneous as iOS but just after some milliseconds (< ~100ms). ///Inside the `window.addEventListener("flutterInAppWebViewPlatformReady")` event, the ajax requests will be intercept for sure. final Future Function( - InAppWebViewController controller, AjaxRequest ajaxRequest) - onAjaxReadyStateChange; + InAppWebViewController controller, AjaxRequest ajaxRequest) + onAjaxReadyStateChange; ///Event fired as an `XMLHttpRequest` progress. ///It gives the host application a chance to abort the request. @@ -248,8 +248,8 @@ abstract class WebView { ///used to intercept ajax requests is loaded as soon as possible so it won't be instantaneous as iOS but just after some milliseconds (< ~100ms). ///Inside the `window.addEventListener("flutterInAppWebViewPlatformReady")` event, the ajax requests will be intercept for sure. final Future Function( - InAppWebViewController controller, AjaxRequest ajaxRequest) - onAjaxProgress; + InAppWebViewController controller, AjaxRequest ajaxRequest) + onAjaxProgress; ///Event fired when a request is sent to a server through [Fetch API](https://developer.mozilla.org/it/docs/Web/API/Fetch_API). ///It gives the host application a chance to take control over the request before sending it. @@ -262,8 +262,8 @@ abstract class WebView { ///used to intercept fetch requests is loaded as soon as possible so it won't be instantaneous as iOS but just after some milliseconds (< ~100ms). ///Inside the `window.addEventListener("flutterInAppWebViewPlatformReady")` event, the fetch requests will be intercept for sure. final Future Function( - InAppWebViewController controller, FetchRequest fetchRequest) - shouldInterceptFetchRequest; + InAppWebViewController controller, FetchRequest fetchRequest) + shouldInterceptFetchRequest; ///Event fired when the host application updates its visited links database. ///This event is also fired when the navigation state of the [WebView] changes through the usage of @@ -276,8 +276,8 @@ abstract class WebView { /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#doUpdateVisitedHistory(android.webkit.WebView,%20java.lang.String,%20boolean) final void Function( - InAppWebViewController controller, String url, bool androidIsReload) - onUpdateVisitedHistory; + InAppWebViewController controller, String url, bool androidIsReload) + onUpdateVisitedHistory; ///Event fired when `window.print()` is called from JavaScript side. /// @@ -316,7 +316,8 @@ abstract class WebView { /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onPageCommitVisible(android.webkit.WebView,%20java.lang.String) ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455635-webview - final Future Function(InAppWebViewController controller, String url) onPageCommitVisible; + final Future Function(InAppWebViewController controller, String url) + onPageCommitVisible; ///Event fired when the webview notifies that a loading URL has been flagged by Safe Browsing. ///The default behavior is to show an interstitial to the user, with the reporting checkbox visible. @@ -355,8 +356,8 @@ abstract class WebView { /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String,%20android.webkit.GeolocationPermissions.Callback) final Future Function( - InAppWebViewController controller, String origin) - androidOnGeolocationPermissionsShowPrompt; + InAppWebViewController controller, String origin) + androidOnGeolocationPermissionsShowPrompt; ///Notify the host application that a request for Geolocation permissions, made with a previous call to [androidOnGeolocationPermissionsShowPrompt] has been canceled. ///Any related UI should therefore be hidden. @@ -365,7 +366,7 @@ abstract class WebView { /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsHidePrompt() final Future Function(InAppWebViewController controller) - androidOnGeolocationPermissionsHidePrompt; + androidOnGeolocationPermissionsHidePrompt; ///Notify the host application of a resource request and allow the application to return the data. ///If the return value is `null`, the WebView will continue to load the resource as usual. @@ -384,8 +385,9 @@ abstract class WebView { ///**Official Android API**: ///- https://developer.android.com/reference/android/webkit/WebViewClient#shouldInterceptRequest(android.webkit.WebView,%20android.webkit.WebResourceRequest) ///- https://developer.android.com/reference/android/webkit/WebViewClient#shouldInterceptRequest(android.webkit.WebView,%20java.lang.String) - final Future Function(InAppWebViewController controller, WebResourceRequest request) - androidShouldInterceptRequest; + final Future Function( + InAppWebViewController controller, WebResourceRequest request) + androidShouldInterceptRequest; ///Event called when the renderer currently associated with the WebView becomes unresponsive as a result of a long running blocking task such as the execution of JavaScript. /// @@ -405,8 +407,9 @@ abstract class WebView { ///**NOTE**: available only on Android 29+. /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessUnresponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess) - final Future Function(InAppWebViewController controller, String url) - androidOnRenderProcessUnresponsive; + final Future Function( + InAppWebViewController controller, String url) + androidOnRenderProcessUnresponsive; ///Event called once when an unresponsive renderer currently associated with the WebView becomes responsive. /// @@ -419,8 +422,9 @@ abstract class WebView { ///**NOTE**: available only on Android 29+. /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessResponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess) - final Future Function(InAppWebViewController controller, String url) - androidOnRenderProcessResponsive; + final Future Function( + InAppWebViewController controller, String url) + androidOnRenderProcessResponsive; ///Event fired when the given WebView's render process has exited. ///The application's implementation of this callback should only attempt to clean up the WebView. @@ -431,16 +435,17 @@ abstract class WebView { ///**NOTE**: available only on Android 26+. /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onRenderProcessGone(android.webkit.WebView,%20android.webkit.RenderProcessGoneDetail) - final Future Function(InAppWebViewController controller, RenderProcessGoneDetail detail) - androidOnRenderProcessGone; + final Future Function( + InAppWebViewController controller, RenderProcessGoneDetail detail) + androidOnRenderProcessGone; ///As the host application if the browser should resend data as the requested page was a result of a POST. The default is to not resend the data. /// ///**NOTE**: available only on Android. /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onFormResubmission(android.webkit.WebView,%20android.os.Message,%20android.os.Message) - final Future Function(InAppWebViewController controller, String url) - androidOnFormResubmission; + final Future Function( + InAppWebViewController controller, String url) androidOnFormResubmission; ///Event fired when the scale applied to the WebView has changed. /// @@ -451,8 +456,9 @@ abstract class WebView { ///**NOTE**: available only on Android. /// ///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onScaleChanged(android.webkit.WebView,%20float,%20float) - final Future Function(InAppWebViewController controller, double oldScale, double newScale) - androidOnScaleChanged; + final Future Function( + InAppWebViewController controller, double oldScale, double newScale) + androidOnScaleChanged; ///Invoked when the web view's web content process is terminated. /// @@ -460,7 +466,7 @@ abstract class WebView { /// ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455639-webviewwebcontentprocessdidtermi final Future Function(InAppWebViewController controller) - iosOnWebContentProcessDidTerminate; + iosOnWebContentProcessDidTerminate; ///Called when a web view receives a server redirect. /// @@ -468,7 +474,7 @@ abstract class WebView { /// ///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455627-webview final Future Function(InAppWebViewController controller) - iosOnDidReceiveServerRedirectForProvisionalNavigation; + iosOnDidReceiveServerRedirectForProvisionalNavigation; ///Initial url that will be loaded. final String initialUrl; @@ -488,54 +494,53 @@ abstract class WebView { ///Context menu which contains custom menu items to be shown when [ContextMenu] is presented. final ContextMenu contextMenu; - WebView({ - this.onWebViewCreated, - this.onLoadStart, - this.onLoadStop, - this.onLoadError, - this.onLoadHttpError, - this.onProgressChanged, - this.onConsoleMessage, - this.shouldOverrideUrlLoading, - this.onLoadResource, - this.onScrollChanged, - this.onDownloadStart, - this.onLoadResourceCustomScheme, - this.onCreateWindow, - this.onJsAlert, - this.onJsConfirm, - this.onJsPrompt, - this.onReceivedHttpAuthRequest, - this.onReceivedServerTrustAuthRequest, - this.onReceivedClientCertRequest, - this.onFindResultReceived, - this.shouldInterceptAjaxRequest, - this.onAjaxReadyStateChange, - this.onAjaxProgress, - this.shouldInterceptFetchRequest, - this.onUpdateVisitedHistory, - this.onPrint, - this.onLongPressHitTestResult, - this.onEnterFullscreen, - this.onExitFullscreen, - this.onPageCommitVisible, - this.androidOnSafeBrowsingHit, - this.androidOnPermissionRequest, - this.androidOnGeolocationPermissionsShowPrompt, - this.androidOnGeolocationPermissionsHidePrompt, - this.androidShouldInterceptRequest, - this.androidOnRenderProcessGone, - this.androidOnRenderProcessResponsive, - this.androidOnRenderProcessUnresponsive, - this.androidOnFormResubmission, - this.androidOnScaleChanged, - this.iosOnWebContentProcessDidTerminate, - this.iosOnDidReceiveServerRedirectForProvisionalNavigation, - this.initialUrl, - this.initialFile, - this.initialData, - this.initialHeaders, - this.initialOptions, - this.contextMenu - }); -} \ No newline at end of file + WebView( + {this.onWebViewCreated, + this.onLoadStart, + this.onLoadStop, + this.onLoadError, + this.onLoadHttpError, + this.onProgressChanged, + this.onConsoleMessage, + this.shouldOverrideUrlLoading, + this.onLoadResource, + this.onScrollChanged, + this.onDownloadStart, + this.onLoadResourceCustomScheme, + this.onCreateWindow, + this.onJsAlert, + this.onJsConfirm, + this.onJsPrompt, + this.onReceivedHttpAuthRequest, + this.onReceivedServerTrustAuthRequest, + this.onReceivedClientCertRequest, + this.onFindResultReceived, + this.shouldInterceptAjaxRequest, + this.onAjaxReadyStateChange, + this.onAjaxProgress, + this.shouldInterceptFetchRequest, + this.onUpdateVisitedHistory, + this.onPrint, + this.onLongPressHitTestResult, + this.onEnterFullscreen, + this.onExitFullscreen, + this.onPageCommitVisible, + this.androidOnSafeBrowsingHit, + this.androidOnPermissionRequest, + this.androidOnGeolocationPermissionsShowPrompt, + this.androidOnGeolocationPermissionsHidePrompt, + this.androidShouldInterceptRequest, + this.androidOnRenderProcessGone, + this.androidOnRenderProcessResponsive, + this.androidOnRenderProcessUnresponsive, + this.androidOnFormResubmission, + this.androidOnScaleChanged, + this.iosOnWebContentProcessDidTerminate, + this.iosOnDidReceiveServerRedirectForProvisionalNavigation, + this.initialUrl, + this.initialFile, + this.initialData, + this.initialHeaders, + this.initialOptions, + this.contextMenu}); +} diff --git a/lib/src/webview_options.dart b/lib/src/webview_options.dart index 800851b3..a9061c9a 100755 --- a/lib/src/webview_options.dart +++ b/lib/src/webview_options.dart @@ -16,6 +16,15 @@ class WebViewOptions { static WebViewOptions fromMap(Map map) { return null; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } class BrowserOptions { @@ -26,6 +35,15 @@ class BrowserOptions { static BrowserOptions fromMap(Map map) { return null; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } class ChromeSafariBrowserOptions { @@ -36,6 +54,15 @@ class ChromeSafariBrowserOptions { static ChromeSafariBrowserOptions fromMap(Map map) { return null; } + + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///This class represents all the cross-platform WebView options available. @@ -148,8 +175,7 @@ class InAppWebViewOptions this.horizontalScrollBarEnabled = true, this.resourceCustomSchemes = const [], this.contentBlockers = const [], - this.preferredContentMode = - UserPreferredContentMode.RECOMMENDED, + this.preferredContentMode = UserPreferredContentMode.RECOMMENDED, this.useShouldInterceptAjaxRequest = false, this.useShouldInterceptFetchRequest = false, this.incognito = false, @@ -229,8 +255,7 @@ class InAppWebViewOptions List.from(map["resourceCustomSchemes"] ?? []); options.contentBlockers = contentBlockers; options.preferredContentMode = - UserPreferredContentMode.fromValue( - map["preferredContentMode"]); + UserPreferredContentMode.fromValue(map["preferredContentMode"]); options.useShouldInterceptAjaxRequest = map["useShouldInterceptAjaxRequest"]; options.useShouldInterceptFetchRequest = @@ -243,6 +268,16 @@ class InAppWebViewOptions options.disableContextMenu = map["disableContextMenu"]; return options; } + + @override + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///This class represents all the Android-only WebView options available. @@ -503,7 +538,8 @@ class AndroidInAppWebViewOptions this.overScrollMode = AndroidOverScrollMode.OVER_SCROLL_IF_CONTENT_SCROLLS, this.networkAvailable, this.scrollBarStyle = AndroidScrollBarStyle.SCROLLBARS_INSIDE_OVERLAY, - this.verticalScrollbarPosition = AndroidVerticalScrollbarPosition.SCROLLBAR_POSITION_DEFAULT, + this.verticalScrollbarPosition = + AndroidVerticalScrollbarPosition.SCROLLBAR_POSITION_DEFAULT, this.scrollBarDefaultDelayBeforeFade, this.scrollbarFadingEnabled = true, this.scrollBarFadeDuration, @@ -589,19 +625,16 @@ class AndroidInAppWebViewOptions options.appCachePath = map["appCachePath"]; options.blockNetworkImage = map["blockNetworkImage"]; options.blockNetworkLoads = map["blockNetworkLoads"]; - options.cacheMode = - AndroidCacheMode.fromValue(map["cacheMode"]); + options.cacheMode = AndroidCacheMode.fromValue(map["cacheMode"]); options.cursiveFontFamily = map["cursiveFontFamily"]; options.defaultFixedFontSize = map["defaultFixedFontSize"]; options.defaultFontSize = map["defaultFontSize"]; options.defaultTextEncodingName = map["defaultTextEncodingName"]; options.disabledActionModeMenuItems = - AndroidActionModeMenuItem.fromValue( - map["disabledActionModeMenuItems"]); + AndroidActionModeMenuItem.fromValue(map["disabledActionModeMenuItems"]); options.fantasyFontFamily = map["fantasyFontFamily"]; options.fixedFontFamily = map["fixedFontFamily"]; - options.forceDark = - AndroidForceDark.fromValue(map["forceDark"]); + options.forceDark = AndroidForceDark.fromValue(map["forceDark"]); options.geolocationEnabled = map["geolocationEnabled"]; options.layoutAlgorithm = AndroidLayoutAlgorithm.fromValue(map["layoutAlgorithm"]); @@ -618,19 +651,36 @@ class AndroidInAppWebViewOptions options.thirdPartyCookiesEnabled = map["thirdPartyCookiesEnabled"]; options.hardwareAcceleration = map["hardwareAcceleration"]; options.supportMultipleWindows = map["supportMultipleWindows"]; - options.regexToCancelSubFramesLoading = map["regexToCancelSubFramesLoading"]; + options.regexToCancelSubFramesLoading = + map["regexToCancelSubFramesLoading"]; options.useShouldInterceptRequest = map["useShouldInterceptRequest"]; options.useOnRenderProcessGone = map["useOnRenderProcessGone"]; - options.overScrollMode = AndroidOverScrollMode.fromValue(map["overScrollMode"]); + options.overScrollMode = + AndroidOverScrollMode.fromValue(map["overScrollMode"]); options.networkAvailable = map["networkAvailable"]; - options.scrollBarStyle = AndroidScrollBarStyle.fromValue(map["scrollBarStyle"]); - options.verticalScrollbarPosition = AndroidVerticalScrollbarPosition.fromValue(map["verticalScrollbarPosition"]); - options.scrollBarDefaultDelayBeforeFade = map["scrollBarDefaultDelayBeforeFade"]; + options.scrollBarStyle = + AndroidScrollBarStyle.fromValue(map["scrollBarStyle"]); + options.verticalScrollbarPosition = + AndroidVerticalScrollbarPosition.fromValue( + map["verticalScrollbarPosition"]); + options.scrollBarDefaultDelayBeforeFade = + map["scrollBarDefaultDelayBeforeFade"]; options.scrollbarFadingEnabled = map["scrollbarFadingEnabled"]; options.scrollBarFadeDuration = map["scrollBarFadeDuration"]; - options.rendererPriorityPolicy = RendererPriorityPolicy.fromMap(map["rendererPriorityPolicy"]?.cast()); + options.rendererPriorityPolicy = RendererPriorityPolicy.fromMap( + map["rendererPriorityPolicy"]?.cast()); return options; } + + @override + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///This class represents all the iOS-only WebView options available. @@ -786,7 +836,8 @@ class IOSInAppWebViewOptions "selectionGranularity": selectionGranularity.toValue(), "dataDetectorTypes": dataDetectorTypesList, "sharedCookiesEnabled": sharedCookiesEnabled, - "automaticallyAdjustsScrollIndicatorInsets": automaticallyAdjustsScrollIndicatorInsets, + "automaticallyAdjustsScrollIndicatorInsets": + automaticallyAdjustsScrollIndicatorInsets, "accessibilityIgnoresInvertColors": accessibilityIgnoresInvertColors, "decelerationRate": decelerationRate.toValue(), "alwaysBounceVertical": alwaysBounceVertical, @@ -803,8 +854,7 @@ class IOSInAppWebViewOptions List dataDetectorTypesList = List.from(map["dataDetectorTypes"] ?? []); dataDetectorTypesList.forEach((dataDetectorType) { - dataDetectorTypes - .add(IOSWKDataDetectorTypes.fromValue(dataDetectorType)); + dataDetectorTypes.add(IOSWKDataDetectorTypes.fromValue(dataDetectorType)); }); IOSInAppWebViewOptions options = IOSInAppWebViewOptions(); @@ -824,13 +874,15 @@ class IOSInAppWebViewOptions options.isFraudulentWebsiteWarningEnabled = map["isFraudulentWebsiteWarningEnabled"]; options.selectionGranularity = - IOSWKSelectionGranularity.fromValue( - map["selectionGranularity"]); + IOSWKSelectionGranularity.fromValue(map["selectionGranularity"]); options.dataDetectorTypes = dataDetectorTypes; options.sharedCookiesEnabled = map["sharedCookiesEnabled"]; - options.automaticallyAdjustsScrollIndicatorInsets = map["automaticallyAdjustsScrollIndicatorInsets"]; - options.accessibilityIgnoresInvertColors = map["accessibilityIgnoresInvertColors"]; - options.decelerationRate = IOSUIScrollViewDecelerationRate.fromValue(map["decelerationRate"]); + options.automaticallyAdjustsScrollIndicatorInsets = + map["automaticallyAdjustsScrollIndicatorInsets"]; + options.accessibilityIgnoresInvertColors = + map["accessibilityIgnoresInvertColors"]; + options.decelerationRate = + IOSUIScrollViewDecelerationRate.fromValue(map["decelerationRate"]); options.alwaysBounceVertical = map["alwaysBounceVertical"]; options.alwaysBounceHorizontal = map["alwaysBounceHorizontal"]; options.scrollsToTop = map["scrollsToTop"]; @@ -839,6 +891,16 @@ class IOSInAppWebViewOptions options.minimumZoomScale = map["minimumZoomScale"]; return options; } + + @override + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///This class represents all the cross-platform [InAppBrowser] options available. @@ -881,6 +943,16 @@ class InAppBrowserOptions options.hideUrlBar = map["hideUrlBar"]; return options; } + + @override + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///This class represents all the Android-only [InAppBrowser] options available. @@ -921,6 +993,16 @@ class AndroidInAppBrowserOptions implements BrowserOptions, AndroidOptions { options.progressBar = map["progressBar"]; return options; } + + @override + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///This class represents all the iOS-only [InAppBrowser] options available. @@ -987,6 +1069,16 @@ class IOSInAppBrowserOptions implements BrowserOptions, IosOptions { options.spinner = map["spinner"]; return options; } + + @override + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///This class represents all the Android-only [ChromeSafariBrowser] options available. @@ -1051,6 +1143,16 @@ class AndroidChromeCustomTabsOptions options.keepAliveEnabled = map["keepAliveEnabled"]; return options; } + + @override + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } } ///This class represents all the iOS-only [ChromeSafariBrowser] options available. @@ -1118,4 +1220,14 @@ class IOSSafariOptions implements ChromeSafariBrowserOptions, IosOptions { IOSUIModalTransitionStyle.fromValue(map["transitionStyle"]); return options; } + + @override + Map toJson() { + return this.toMap(); + } + + @override + String toString() { + return toMap().toString(); + } }