Commit ad56ca66 authored by Lorenzo Pichilli's avatar Lorenzo Pichilli

Added 'toString()' method to various classes in order to have a better output...

Added 'toString()' method to various classes in order to have a better output instead of simply 'Instance of ...', updated getOptions() method
parent 7d88cd80
## 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
......
......@@ -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) {
......
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 {
final static String LOG_TAG = "ChromeCustomTabsOptions";
public class ChromeCustomTabsOptions implements Options<ChromeCustomTabsActivity> {
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;
final static String LOG_TAG = "ChromeCustomTabsOptions";
@Override
public ChromeCustomTabsOptions parse(HashMap<String, Object> options) {
for (Map.Entry<String, Object> pair : options.entrySet()) {
String key = pair.getKey();
Object value = pair.getValue();
if (value == null) {
continue;
}
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;
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 ChromeCustomTabsOptions parse(Map<String, Object> options) {
for (Map.Entry<String, Object> pair : options.entrySet()) {
String key = pair.getKey();
Object value = pair.getValue();
if (value == null) {
continue;
}
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<String, Object> getHashMap() {
HashMap<String, Object> 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<String, Object> toMap() {
Map<String, Object> 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<String, Object> getRealOptions(ChromeCustomTabsActivity chromeCustomTabsActivity) {
Map<String, Object> 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;
}
}
......@@ -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;
......
......@@ -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);
}
......
......@@ -707,12 +707,12 @@ public class InAppBrowserActivity extends AppCompatActivity implements MethodCha
options = newOptions;
}
public HashMap<String, Object> getOptions() {
HashMap<String, Object> webViewOptionsMap = webView.getOptions();
public Map<String, Object> getOptions() {
Map<String, Object> webViewOptionsMap = webView.getOptions();
if (options == null || webViewOptionsMap == null)
return null;
HashMap<String, Object> optionsMap = options.getHashMap();
Map<String, Object> optionsMap = options.getRealOptions(this);
optionsMap.putAll(webViewOptionsMap);
return optionsMap;
}
......
......@@ -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<InAppBrowserActivity> {
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<String, Object> options) {
public InAppBrowserOptions parse(Map<String, Object> options) {
for (Map.Entry<String, Object> pair : options.entrySet()) {
String key = pair.getKey();
Object value = pair.getValue();
......@@ -60,8 +60,8 @@ public class InAppBrowserOptions implements Options {
}
@Override
public HashMap<String, Object> getHashMap() {
HashMap<String, Object> options = new HashMap<>();
public Map<String, Object> toMap() {
Map<String, Object> 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<String, Object> getRealOptions(InAppBrowserActivity inAppBrowserActivity) {
Map<String, Object> realOptions = toMap();
return realOptions;
}
}
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<String, Object> getOptions() {
return (options != null) ? options.getHashMap() : null;
public Map<String, Object> getOptions() {
return (options != null) ? options.getRealOptions(this) : null;
}
public void injectDeferredObject(String source, String jsWrapper, final MethodChannel.Result result) {
......
......@@ -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<InAppWebView> {
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<String, Object> options) {
public InAppWebViewOptions parse(Map<String, Object> options) {
for (Map.Entry<String, Object> pair : options.entrySet()) {
String key = pair.getKey();
Object value = pair.getValue();
......@@ -343,8 +342,8 @@ public class InAppWebViewOptions implements Options {
}
@Override
public HashMap<String, Object> getHashMap() {
HashMap<String, Object> options = new HashMap<>();
public Map<String, Object> toMap() {
Map<String, Object> 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<String, Object> getRealOptions(InAppWebView webView) {
Map<String, Object> 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<String, Object> 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;
......
package com.pichillilorenzo.flutter_inappwebview;
import java.util.HashMap;
import java.util.Map;
public interface Options {
public interface Options<T> {
static String LOG_TAG = "Options";
public Options parse(HashMap<String, Object> options);
public HashMap<String, Object> getHashMap();
public Options parse(Map<String, Object> options);
public Map<String, Object> toMap();
public Map<String, Object> getRealOptions(T webView);
}
{"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
......@@ -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<ChromeSafariBrowserExampleScreen> {
@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);
......
......@@ -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 ?? [:])
}
}
}
......@@ -8,7 +8,7 @@
import Foundation
@objcMembers
public class InAppBrowserOptions: Options {
public class InAppBrowserOptions: Options<InAppBrowserWebViewController> {
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
}
}
......@@ -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
}
......
......@@ -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() {
......
......@@ -9,7 +9,7 @@ import Foundation
import WebKit
@objcMembers
public class InAppWebViewOptions: Options {
public class InAppWebViewOptions: Options<InAppWebView> {
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
}
}
......@@ -8,7 +8,7 @@
import Foundation
@objcMembers
public class Options: NSObject {
public class Options<T>: 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
}
}
......@@ -7,8 +7,9 @@
import Foundation
@available(iOS 9.0, *)
@objcMembers
public class SafariBrowserOptions: Options {
public class SafariBrowserOptions: Options<SafariViewController> {
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
}
}
......@@ -17,7 +17,8 @@ class ChromeSafariBrowser {
Map<int, ChromeSafariBrowserMenuItem> _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<Map<String, dynamic>> menuItemList = new List();
_menuItems.forEach((key, value) {
menuItemList.add({
"id": value.id,
"label": value.label
});
menuItemList.add({"id": value.id, "label": value.label});
});
Map<String, dynamic> args = <String, dynamic>{};
......@@ -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<String, dynamic> toMap() {
return {"id": id, "label": label};
}
Map<String, dynamic> toJson() {
return this.toMap();
}
@override
String toString() {
return toMap().toString();
}
}
......@@ -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<ContextMenuItem> menuItems = List();
ContextMenu({
this.menuItems,
this.onCreateContextMenu,
this.onHideContextMenu,
this.onContextMenuActionItemClicked
});
ContextMenu(
{this.menuItems,
this.onCreateContextMenu,
this.onHideContextMenu,
this.onContextMenuActionItemClicked});
Map<String, dynamic> 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<String, dynamic> toMap() {
return {
"androidId": androidId,
"iosId": iosId,
"title": title
};
return {"androidId": androidId, "iosId": iosId, "title": title};
}
Map<String, dynamic> toJson() {
......
......@@ -22,7 +22,7 @@ class CookieManager {
static CookieManager _init() {
_channel.setMethodCallHandler(_handleMethod);
_instance = new CookieManager();
_instance = CookieManager();
return _instance;
}
......
This diff is collapsed.
......@@ -22,7 +22,7 @@ class HttpAuthCredentialDatabase {
static HttpAuthCredentialDatabase _init() {
_channel.setMethodCallHandler(_handleMethod);
_instance = new HttpAuthCredentialDatabase();
_instance = HttpAuthCredentialDatabase();
return _instance;
}
......
......@@ -23,7 +23,8 @@ class InAppBrowser {
HashMap<String, JavaScriptHandlerCallback>();
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<dynamic> handleMethod(MethodCall call) async {
......@@ -117,8 +118,6 @@ class InAppBrowser {
assert(assetFilePath != null && assetFilePath.isNotEmpty);
this.throwIsAlreadyOpened(message: 'Cannot open $assetFilePath!');
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('uuid', () => uuid);
args.putIfAbsent('url', () => assetFilePath);
......@@ -217,20 +216,19 @@ class InAppBrowser {
options = options.cast<String, dynamic>();
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<ShouldOverrideUrlLoadingAction> shouldOverrideUrlLoading(ShouldOverrideUrlLoadingRequest shouldOverrideUrlLoadingRequest) {}
Future<ShouldOverrideUrlLoadingAction> 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<GeolocationPermissionShowPromptResponse>
// 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<WebResourceResponse>
// 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<WebViewRenderProcessAction>
// 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<WebViewRenderProcessAction>
// 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<FormResubmissionAction>
// ignore: missing_return
androidOnFormResubmission(String url) {}
// ignore: missing_return
androidOnFormResubmission(String url) {}
///Event fired when the scale applied to the WebView has changed.
///
......
......@@ -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();
});
......
......@@ -116,7 +116,8 @@ class InAppWebView extends StatefulWidget implements WebView {
final ContextMenu contextMenu;
@override
final Future<void> Function(InAppWebViewController controller, String url) onPageCommitVisible;
final Future<void> Function(InAppWebViewController controller, String url)
onPageCommitVisible;
@override
final Future<void> Function(InAppWebViewController controller)
......@@ -251,28 +252,33 @@ class InAppWebView extends StatefulWidget implements WebView {
final void Function(InAppWebViewController controller) onExitFullscreen;
@override
final Future<WebResourceResponse> Function(InAppWebViewController controller, WebResourceRequest request)
androidShouldInterceptRequest;
final Future<WebResourceResponse> Function(
InAppWebViewController controller, WebResourceRequest request)
androidShouldInterceptRequest;
@override
final Future<WebViewRenderProcessAction> Function(InAppWebViewController controller, String url)
androidOnRenderProcessUnresponsive;
final Future<WebViewRenderProcessAction> Function(
InAppWebViewController controller, String url)
androidOnRenderProcessUnresponsive;
@override
final Future<WebViewRenderProcessAction> Function(InAppWebViewController controller, String url)
androidOnRenderProcessResponsive;
final Future<WebViewRenderProcessAction> Function(
InAppWebViewController controller, String url)
androidOnRenderProcessResponsive;
@override
final Future<void> Function(InAppWebViewController controller, RenderProcessGoneDetail detail)
androidOnRenderProcessGone;
final Future<void> Function(
InAppWebViewController controller, RenderProcessGoneDetail detail)
androidOnRenderProcessGone;
@override
final Future<FormResubmissionAction> Function(InAppWebViewController controller, String url)
androidOnFormResubmission;
final Future<FormResubmissionAction> Function(
InAppWebViewController controller, String url) androidOnFormResubmission;
@override
final Future<void> Function(InAppWebViewController controller, double oldScale, double newScale)
androidOnScaleChanged;
final Future<void> Function(
InAppWebViewController controller, double oldScale, double newScale)
androidOnScaleChanged;
}
class _InAppWebViewState extends State<InAppWebView> {
......
......@@ -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<String> saveWebArchive({@required String basename, @required bool autoname}) async {
Future<String> saveWebArchive(
{@required String basename, @required bool autoname}) async {
assert(basename != null && autoname != null);
Map<String, dynamic> args = <String, dynamic>{};
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<AndroidWebViewPackageInfo> getCurrentWebViewPackage() async {
Map<String, dynamic> args = <String, dynamic>{};
Map<String, dynamic> packageInfo = (await InAppWebViewController._staticChannel.invokeMethod('getCurrentWebViewPackage', args))?.cast<String, dynamic>();
Map<String, dynamic> packageInfo = (await InAppWebViewController
._staticChannel
.invokeMethod('getCurrentWebViewPackage', args))
?.cast<String, dynamic>();
return AndroidWebViewPackageInfo.fromMap(packageInfo);
}
}
......
This diff is collapsed.
......@@ -40,10 +40,15 @@ class AndroidWebStorageManager {
List<AndroidWebStorageOrigin> originsList = [];
Map<String, dynamic> args = <String, dynamic>{};
List<Map<dynamic, dynamic>> origins = (await WebStorageManager._channel.invokeMethod('getOrigins', args)).cast<Map<dynamic, dynamic>>();
for(var origin in origins) {
originsList.add(AndroidWebStorageOrigin(origin: origin["origin"], quota: origin["quota"], usage: origin["usage"]));
List<Map<dynamic, dynamic>> origins =
(await WebStorageManager._channel.invokeMethod('getOrigins', args))
.cast<Map<dynamic, dynamic>>();
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<String, dynamic> args = <String, dynamic>{};
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<String, dynamic> args = <String, dynamic>{};
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<List<IOSWKWebsiteDataRecord>> fetchDataRecords({@required Set<IOSWKWebsiteDataType> dataTypes}) async {
Future<List<IOSWKWebsiteDataRecord>> fetchDataRecords(
{@required Set<IOSWKWebsiteDataType> dataTypes}) async {
assert(dataTypes != null);
List<IOSWKWebsiteDataRecord> recordList = [];
List<String> dataTypesList = [];
......@@ -102,14 +110,17 @@ class IOSWebStorageManager {
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("dataTypes", () => dataTypesList);
List<Map<dynamic, dynamic>> records = (await WebStorageManager._channel.invokeMethod('fetchDataRecords', args)).cast<Map<dynamic, dynamic>>();
for(var record in records) {
List<Map<dynamic, dynamic>> records = (await WebStorageManager._channel
.invokeMethod('fetchDataRecords', args))
.cast<Map<dynamic, dynamic>>();
for (var record in records) {
List<String> dataTypesString = record["dataTypes"].cast<String>();
Set<IOSWKWebsiteDataType> 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<void> removeDataFor({@required Set<IOSWKWebsiteDataType> dataTypes, @required List<IOSWKWebsiteDataRecord> dataRecords}) async {
Future<void> removeDataFor(
{@required Set<IOSWKWebsiteDataType> dataTypes,
@required List<IOSWKWebsiteDataRecord> dataRecords}) async {
assert(dataTypes != null && dataRecords != null);
List<String> 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<void> removeDataModifiedSince({@required Set<IOSWKWebsiteDataType> dataTypes, @required DateTime date}) async {
Future<void> removeDataModifiedSince(
{@required Set<IOSWKWebsiteDataType> dataTypes,
@required DateTime date}) async {
assert(dataTypes != null && date != null);
List<String> dataTypesList = [];
......@@ -156,6 +171,7 @@ class IOSWebStorageManager {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("dataTypes", () => dataTypesList);
args.putIfAbsent("timestamp", () => timestamp);
await WebStorageManager._channel.invokeMethod('removeDataModifiedSince', args);
await WebStorageManager._channel
.invokeMethod('removeDataModifiedSince', args);
}
}
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment