initial refactor

This commit is contained in:
Lorenzo Pichilli 2022-04-20 01:31:14 +02:00
parent a866cd6b24
commit 5371b77231
64 changed files with 7356 additions and 2281 deletions

View File

@ -2,8 +2,8 @@ package com.pichillilorenzo.flutter_inappwebview;
import java.util.Map;
public interface Options<T> {
public Options parse(Map<String, Object> options);
public interface IWebViewSettings<T> {
public IWebViewSettings parse(Map<String, Object> settings);
public Map<String, Object> toMap();
public Map<String, Object> getRealOptions(T obj);
public Map<String, Object> getRealSettings(T obj);
}

View File

@ -12,16 +12,15 @@ import androidx.webkit.WebViewCompat;
import androidx.webkit.WebViewFeature;
import com.pichillilorenzo.flutter_inappwebview.in_app_browser.InAppBrowserActivity;
import com.pichillilorenzo.flutter_inappwebview.in_app_browser.InAppBrowserOptions;
import com.pichillilorenzo.flutter_inappwebview.in_app_browser.InAppBrowserSettings;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebView;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebViewOptions;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebViewSettings;
import com.pichillilorenzo.flutter_inappwebview.types.ContentWorld;
import com.pichillilorenzo.flutter_inappwebview.types.HitTestResult;
import com.pichillilorenzo.flutter_inappwebview.types.InAppWebViewInterface;
import com.pichillilorenzo.flutter_inappwebview.types.SslCertificateExt;
import com.pichillilorenzo.flutter_inappwebview.types.URLRequest;
import com.pichillilorenzo.flutter_inappwebview.types.UserScript;
import com.pichillilorenzo.flutter_inappwebview.types.WebMessage;
import com.pichillilorenzo.flutter_inappwebview.types.WebMessageChannel;
import com.pichillilorenzo.flutter_inappwebview.types.WebMessageListener;
import com.pichillilorenzo.flutter_inappwebview.types.WebMessagePort;
@ -179,27 +178,27 @@ public class InAppWebViewMethodHandler implements MethodChannel.MethodCallHandle
else
result.success(null);
break;
case "setOptions":
case "setSettings":
if (webView != null && webView.getInAppBrowserDelegate() != null && webView.getInAppBrowserDelegate() instanceof InAppBrowserActivity) {
InAppBrowserActivity inAppBrowserActivity = (InAppBrowserActivity) webView.getInAppBrowserDelegate();
InAppBrowserOptions inAppBrowserOptions = new InAppBrowserOptions();
HashMap<String, Object> inAppBrowserOptionsMap = (HashMap<String, Object>) call.argument("options");
inAppBrowserOptions.parse(inAppBrowserOptionsMap);
inAppBrowserActivity.setOptions(inAppBrowserOptions, inAppBrowserOptionsMap);
InAppBrowserSettings inAppBrowserSettings = new InAppBrowserSettings();
HashMap<String, Object> inAppBrowserSettingsMap = (HashMap<String, Object>) call.argument("settings");
inAppBrowserSettings.parse(inAppBrowserSettingsMap);
inAppBrowserActivity.setSettings(inAppBrowserSettings, inAppBrowserSettingsMap);
} else if (webView != null) {
InAppWebViewOptions inAppWebViewOptions = new InAppWebViewOptions();
HashMap<String, Object> inAppWebViewOptionsMap = (HashMap<String, Object>) call.argument("options");
inAppWebViewOptions.parse(inAppWebViewOptionsMap);
webView.setOptions(inAppWebViewOptions, inAppWebViewOptionsMap);
InAppWebViewSettings inAppWebViewSettings = new InAppWebViewSettings();
HashMap<String, Object> inAppWebViewSettingsMap = (HashMap<String, Object>) call.argument("settings");
inAppWebViewSettings.parse(inAppWebViewSettingsMap);
webView.setSettings(inAppWebViewSettings, inAppWebViewSettingsMap);
}
result.success(true);
break;
case "getOptions":
case "getSettings":
if (webView != null && webView.getInAppBrowserDelegate() != null && webView.getInAppBrowserDelegate() instanceof InAppBrowserActivity) {
InAppBrowserActivity inAppBrowserActivity = (InAppBrowserActivity) webView.getInAppBrowserDelegate();
result.success(inAppBrowserActivity.getOptions());
result.success(inAppBrowserActivity.getCustomSettings());
} else {
result.success((webView != null) ? webView.getOptions() : null);
result.success((webView != null) ? webView.getCustomSettings() : null);
}
break;
case "close":

View File

@ -7,14 +7,14 @@ import androidx.browser.customtabs.CustomTabsIntent;
import androidx.browser.trusted.ScreenOrientation;
import androidx.browser.trusted.TrustedWebActivityDisplayMode;
import com.pichillilorenzo.flutter_inappwebview.Options;
import com.pichillilorenzo.flutter_inappwebview.IWebViewSettings;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ChromeCustomTabsOptions implements Options<ChromeCustomTabsActivity> {
public class ChromeCustomTabsOptions implements IWebViewSettings<ChromeCustomTabsActivity> {
final static String LOG_TAG = "ChromeCustomTabsOptions";
@ -88,7 +88,7 @@ public class ChromeCustomTabsOptions implements Options<ChromeCustomTabsActivity
switch (displayModeType) {
case "IMMERSIVE_MODE":
boolean isSticky = (boolean) displayModeMap.get("isSticky");
int layoutInDisplayCutoutMode = (int) displayModeMap.get("layoutInDisplayCutoutMode");
int layoutInDisplayCutoutMode = (int) displayModeMap.get("displayCutoutMode");
displayMode = new TrustedWebActivityDisplayMode.ImmersiveMode(isSticky, layoutInDisplayCutoutMode);
case "DEFAULT_MODE":
displayMode = new TrustedWebActivityDisplayMode.DefaultMode();
@ -123,7 +123,7 @@ public class ChromeCustomTabsOptions implements Options<ChromeCustomTabsActivity
}
@Override
public Map<String, Object> getRealOptions(ChromeCustomTabsActivity chromeCustomTabsActivity) {
public Map<String, Object> getRealSettings(ChromeCustomTabsActivity chromeCustomTabsActivity) {
Map<String, Object> realOptions = toMap();
if (chromeCustomTabsActivity != null) {
Intent intent = chromeCustomTabsActivity.getIntent();

View File

@ -2,7 +2,6 @@ package com.pichillilorenzo.flutter_inappwebview.content_blocker;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.WebResourceResponse;
@ -44,7 +43,7 @@ public class ContentBlockerHandler {
}
public WebResourceResponse checkUrl(final InAppWebView webView, String url, ContentBlockerTriggerResourceType responseResourceType) throws URISyntaxException, InterruptedException, MalformedURLException {
if (webView.options.contentBlockers == null)
if (webView.customSettings.contentBlockers == null)
return null;
URI u;

View File

@ -29,7 +29,7 @@ import com.pichillilorenzo.flutter_inappwebview.R;
import com.pichillilorenzo.flutter_inappwebview.Util;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebView;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebViewChromeClient;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebViewOptions;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebViewSettings;
import com.pichillilorenzo.flutter_inappwebview.pull_to_refresh.PullToRefreshLayout;
import com.pichillilorenzo.flutter_inappwebview.pull_to_refresh.PullToRefreshOptions;
import com.pichillilorenzo.flutter_inappwebview.types.URLRequest;
@ -55,7 +55,7 @@ public class InAppBrowserActivity extends AppCompatActivity implements InAppBrow
public ActionBar actionBar;
public Menu menu;
public SearchView searchView;
public InAppBrowserOptions options;
public InAppBrowserSettings customSettings;
public ProgressBar progressBar;
public boolean isHidden = false;
public String fromActivity;
@ -101,16 +101,16 @@ public class InAppBrowserActivity extends AppCompatActivity implements InAppBrow
fromActivity = b.getString("fromActivity");
Map<String, Object> optionsMap = (Map<String, Object>) b.getSerializable("options");
Map<String, Object> settingsMap = (Map<String, Object>) b.getSerializable("settings");
Map<String, Object> contextMenu = (Map<String, Object>) b.getSerializable("contextMenu");
List<Map<String, Object>> initialUserScripts = (List<Map<String, Object>>) b.getSerializable("initialUserScripts");
options = new InAppBrowserOptions();
options.parse(optionsMap);
customSettings = new InAppBrowserSettings();
customSettings.parse(settingsMap);
InAppWebViewOptions webViewOptions = new InAppWebViewOptions();
webViewOptions.parse(optionsMap);
webView.options = webViewOptions;
InAppWebViewSettings webViewSettings = new InAppWebViewSettings();
webViewSettings.parse(settingsMap);
webView.customSettings = webViewSettings;
webView.contextMenu = contextMenu;
List<UserScript> userScripts = new ArrayList<>();
@ -169,29 +169,29 @@ public class InAppBrowserActivity extends AppCompatActivity implements InAppBrow
webView.prepare();
if (options.hidden)
if (customSettings.hidden)
hide();
else
show();
progressBar = findViewById(R.id.progressBar);
if (options.hideProgressBar)
if (customSettings.hideProgressBar)
progressBar.setMax(0);
else
progressBar.setMax(100);
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(!options.hideTitleBar);
actionBar.setDisplayShowTitleEnabled(!customSettings.hideTitleBar);
if (options.hideToolbarTop)
if (customSettings.hideToolbarTop)
actionBar.hide();
if (options.toolbarTopBackgroundColor != null && !options.toolbarTopBackgroundColor.isEmpty())
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(options.toolbarTopBackgroundColor)));
if (customSettings.toolbarTopBackgroundColor != null && !customSettings.toolbarTopBackgroundColor.isEmpty())
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(customSettings.toolbarTopBackgroundColor)));
if (options.toolbarTopFixedTitle != null && !options.toolbarTopFixedTitle.isEmpty())
actionBar.setTitle(options.toolbarTopFixedTitle);
if (customSettings.toolbarTopFixedTitle != null && !customSettings.toolbarTopFixedTitle.isEmpty())
actionBar.setTitle(customSettings.toolbarTopFixedTitle);
}
}
@ -206,12 +206,12 @@ public class InAppBrowserActivity extends AppCompatActivity implements InAppBrow
searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setFocusable(true);
if (options.hideUrlBar)
if (customSettings.hideUrlBar)
menu.findItem(R.id.menu_search).setVisible(false);
searchView.setQuery(webView.getUrl(), false);
if (actionBar != null && (options.toolbarTopFixedTitle == null || options.toolbarTopFixedTitle.isEmpty()))
if (actionBar != null && (customSettings.toolbarTopFixedTitle == null || customSettings.toolbarTopFixedTitle.isEmpty()))
actionBar.setTitle(webView.getTitle());
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@ -257,18 +257,18 @@ public class InAppBrowserActivity extends AppCompatActivity implements InAppBrow
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (options.shouldCloseOnBackButtonPressed) {
if (customSettings.shouldCloseOnBackButtonPressed) {
close(null);
return true;
}
if (options.allowGoBackWithBackButton) {
if (customSettings.allowGoBackWithBackButton) {
if (canGoBack())
goBack();
else if (options.closeOnCannotGoBack)
else if (customSettings.closeOnCannotGoBack)
close(null);
return true;
}
if (!options.shouldCloseOnBackButtonPressed) {
if (!customSettings.shouldCloseOnBackButtonPressed) {
return true;
}
}
@ -355,64 +355,64 @@ public class InAppBrowserActivity extends AppCompatActivity implements InAppBrow
close(null);
}
public void setOptions(InAppBrowserOptions newOptions, HashMap<String, Object> newOptionsMap) {
public void setSettings(InAppBrowserSettings newSettings, HashMap<String, Object> newSettingsMap) {
InAppWebViewOptions newInAppWebViewOptions = new InAppWebViewOptions();
newInAppWebViewOptions.parse(newOptionsMap);
webView.setOptions(newInAppWebViewOptions, newOptionsMap);
InAppWebViewSettings newInAppWebViewSettings = new InAppWebViewSettings();
newInAppWebViewSettings.parse(newSettingsMap);
webView.setSettings(newInAppWebViewSettings, newSettingsMap);
if (newOptionsMap.get("hidden") != null && options.hidden != newOptions.hidden) {
if (newOptions.hidden)
if (newSettingsMap.get("hidden") != null && customSettings.hidden != newSettings.hidden) {
if (newSettings.hidden)
hide();
else
show();
}
if (newOptionsMap.get("hideProgressBar") != null && options.hideProgressBar != newOptions.hideProgressBar && progressBar != null) {
if (newOptions.hideProgressBar)
if (newSettingsMap.get("hideProgressBar") != null && customSettings.hideProgressBar != newSettings.hideProgressBar && progressBar != null) {
if (newSettings.hideProgressBar)
progressBar.setMax(0);
else
progressBar.setMax(100);
}
if (actionBar != null && newOptionsMap.get("hideTitleBar") != null && options.hideTitleBar != newOptions.hideTitleBar)
actionBar.setDisplayShowTitleEnabled(!newOptions.hideTitleBar);
if (actionBar != null && newSettingsMap.get("hideTitleBar") != null && customSettings.hideTitleBar != newSettings.hideTitleBar)
actionBar.setDisplayShowTitleEnabled(!newSettings.hideTitleBar);
if (actionBar != null && newOptionsMap.get("hideToolbarTop") != null && options.hideToolbarTop != newOptions.hideToolbarTop) {
if (newOptions.hideToolbarTop)
if (actionBar != null && newSettingsMap.get("hideToolbarTop") != null && customSettings.hideToolbarTop != newSettings.hideToolbarTop) {
if (newSettings.hideToolbarTop)
actionBar.hide();
else
actionBar.show();
}
if (actionBar != null && newOptionsMap.get("toolbarTopBackgroundColor") != null &&
!Util.objEquals(options.toolbarTopBackgroundColor, newOptions.toolbarTopBackgroundColor) &&
!newOptions.toolbarTopBackgroundColor.isEmpty())
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(newOptions.toolbarTopBackgroundColor)));
if (actionBar != null && newSettingsMap.get("toolbarTopBackgroundColor") != null &&
!Util.objEquals(customSettings.toolbarTopBackgroundColor, newSettings.toolbarTopBackgroundColor) &&
!newSettings.toolbarTopBackgroundColor.isEmpty())
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(newSettings.toolbarTopBackgroundColor)));
if (actionBar != null && newOptionsMap.get("toolbarTopFixedTitle") != null &&
!Util.objEquals(options.toolbarTopFixedTitle, newOptions.toolbarTopFixedTitle) &&
!newOptions.toolbarTopFixedTitle.isEmpty())
actionBar.setTitle(newOptions.toolbarTopFixedTitle);
if (actionBar != null && newSettingsMap.get("toolbarTopFixedTitle") != null &&
!Util.objEquals(customSettings.toolbarTopFixedTitle, newSettings.toolbarTopFixedTitle) &&
!newSettings.toolbarTopFixedTitle.isEmpty())
actionBar.setTitle(newSettings.toolbarTopFixedTitle);
if (newOptionsMap.get("hideUrlBar") != null && options.hideUrlBar != newOptions.hideUrlBar) {
if (newOptions.hideUrlBar)
if (newSettingsMap.get("hideUrlBar") != null && customSettings.hideUrlBar != newSettings.hideUrlBar) {
if (newSettings.hideUrlBar)
menu.findItem(R.id.menu_search).setVisible(false);
else
menu.findItem(R.id.menu_search).setVisible(true);
}
options = newOptions;
customSettings = newSettings;
}
public Map<String, Object> getOptions() {
Map<String, Object> webViewOptionsMap = webView.getOptions();
if (options == null || webViewOptionsMap == null)
public Map<String, Object> getCustomSettings() {
Map<String, Object> webViewSettingsMap = webView.getCustomSettings();
if (customSettings == null || webViewSettingsMap == null)
return null;
Map<String, Object> optionsMap = options.getRealOptions(this);
optionsMap.putAll(webViewOptionsMap);
return optionsMap;
Map<String, Object> settingsMap = customSettings.getRealSettings(this);
settingsMap.putAll(webViewSettingsMap);
return settingsMap;
}
@Override
@ -422,7 +422,7 @@ public class InAppBrowserActivity extends AppCompatActivity implements InAppBrow
@Override
public void didChangeTitle(String title) {
if (actionBar != null && (options.toolbarTopFixedTitle == null || options.toolbarTopFixedTitle.isEmpty())) {
if (actionBar != null && (customSettings.toolbarTopFixedTitle == null || customSettings.toolbarTopFixedTitle.isEmpty())) {
actionBar.setTitle(title);
}
}

View File

@ -8,9 +8,9 @@ import com.pichillilorenzo.flutter_inappwebview.R;
import java.util.HashMap;
import java.util.Map;
public class InAppBrowserOptions implements IWebViewSettings<InAppBrowserActivity> {
public class InAppBrowserSettings implements IWebViewSettings<InAppBrowserActivity> {
public static final String LOG_TAG = "InAppBrowserOptions";
public static final String LOG_TAG = "InAppBrowserSettings";
public Boolean hidden = false;
public Boolean hideToolbarTop = false;
@ -27,8 +27,8 @@ public class InAppBrowserOptions implements IWebViewSettings<InAppBrowserActivit
public Boolean shouldCloseOnBackButtonPressed = false;
@Override
public InAppBrowserOptions parse(Map<String, Object> options) {
for (Map.Entry<String, Object> pair : options.entrySet()) {
public InAppBrowserSettings parse(Map<String, Object> settings) {
for (Map.Entry<String, Object> pair : settings.entrySet()) {
String key = pair.getKey();
Object value = pair.getValue();
if (value == null) {
@ -74,26 +74,26 @@ public class InAppBrowserOptions implements IWebViewSettings<InAppBrowserActivit
@Override
public Map<String, Object> toMap() {
Map<String, Object> options = new HashMap<>();
options.put("hidden", hidden);
options.put("hideToolbarTop", hideToolbarTop);
options.put("toolbarTopBackgroundColor", toolbarTopBackgroundColor);
options.put("toolbarTopFixedTitle", toolbarTopFixedTitle);
options.put("hideUrlBar", hideUrlBar);
options.put("hideTitleBar", hideTitleBar);
options.put("closeOnCannotGoBack", closeOnCannotGoBack);
options.put("hideProgressBar", hideProgressBar);
options.put("allowGoBackWithBackButton", allowGoBackWithBackButton);
options.put("shouldCloseOnBackButtonPressed", shouldCloseOnBackButtonPressed);
return options;
Map<String, Object> settings = new HashMap<>();
settings.put("hidden", hidden);
settings.put("hideToolbarTop", hideToolbarTop);
settings.put("toolbarTopBackgroundColor", toolbarTopBackgroundColor);
settings.put("toolbarTopFixedTitle", toolbarTopFixedTitle);
settings.put("hideUrlBar", hideUrlBar);
settings.put("hideTitleBar", hideTitleBar);
settings.put("closeOnCannotGoBack", closeOnCannotGoBack);
settings.put("hideProgressBar", hideProgressBar);
settings.put("allowGoBackWithBackButton", allowGoBackWithBackButton);
settings.put("shouldCloseOnBackButtonPressed", shouldCloseOnBackButtonPressed);
return settings;
}
@Override
public Map<String, Object> getRealOptions(InAppBrowserActivity inAppBrowserActivity) {
Map<String, Object> realOptions = toMap();
realOptions.put("hideToolbarTop", !inAppBrowserActivity.actionBar.isShowing());
realOptions.put("hideUrlBar", !inAppBrowserActivity.menu.findItem(R.id.menu_search).isVisible());
realOptions.put("hideProgressBar", inAppBrowserActivity.progressBar.getMax() == 0);
return realOptions;
public Map<String, Object> getRealSettings(InAppBrowserActivity inAppBrowserActivity) {
Map<String, Object> realSettings = toMap();
realSettings.put("hideToolbarTop", !inAppBrowserActivity.actionBar.isShowing());
realSettings.put("hideUrlBar", !inAppBrowserActivity.menu.findItem(R.id.menu_search).isVisible());
realSettings.put("hideProgressBar", inAppBrowserActivity.progressBar.getMax() == 0);
return realSettings;
}
}

View File

@ -1,11 +1,11 @@
package com.pichillilorenzo.flutter_inappwebview.in_app_webview;
import com.pichillilorenzo.flutter_inappwebview.Options;
import com.pichillilorenzo.flutter_inappwebview.IWebViewSettings;
import java.util.HashMap;
import java.util.Map;
public class ContextMenuOptions implements Options<Object> {
public class ContextMenuOptions implements IWebViewSettings<Object> {
public static final String LOG_TAG = "ContextMenuOptions";
public Boolean hideDefaultSystemContextMenuItems = false;
@ -35,7 +35,7 @@ public class ContextMenuOptions implements Options<Object> {
}
@Override
public Map<String, Object> getRealOptions(Object obj) {
public Map<String, Object> getRealSettings(Object obj) {
Map<String, Object> realOptions = toMap();
return realOptions;
}

View File

@ -51,14 +51,14 @@ public class FlutterWebView implements PlatformWebView {
DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
displayListenerProxy.onPreWebViewInitialization(displayManager);
Map<String, Object> initialOptions = (Map<String, Object>) params.get("initialOptions");
Map<String, Object> initialSettings = (Map<String, Object>) params.get("initialSettings");
Map<String, Object> contextMenu = (Map<String, Object>) params.get("contextMenu");
Integer windowId = (Integer) params.get("windowId");
List<Map<String, Object>> initialUserScripts = (List<Map<String, Object>>) params.get("initialUserScripts");
Map<String, Object> pullToRefreshInitialOptions = (Map<String, Object>) params.get("pullToRefreshOptions");
InAppWebViewOptions options = new InAppWebViewOptions();
options.parse(initialOptions);
InAppWebViewSettings options = new InAppWebViewSettings();
options.parse(initialSettings);
if (plugin.activity == null) {
Log.e(LOG_TAG, "\n\n\nERROR: You need to upgrade your Flutter project to use the new Java Embedding API:\n\n" +
@ -175,26 +175,26 @@ public class FlutterWebView implements PlatformWebView {
@Override
public void onInputConnectionLocked() {
if (webView != null && webView.inAppBrowserDelegate == null && !webView.options.useHybridComposition)
if (webView != null && webView.inAppBrowserDelegate == null && !webView.customSettings.useHybridComposition)
webView.lockInputConnection();
}
@Override
public void onInputConnectionUnlocked() {
if (webView != null && webView.inAppBrowserDelegate == null && !webView.options.useHybridComposition)
if (webView != null && webView.inAppBrowserDelegate == null && !webView.customSettings.useHybridComposition)
webView.unlockInputConnection();
}
@Override
public void onFlutterViewAttached(@NonNull View flutterView) {
if (webView != null && !webView.options.useHybridComposition) {
if (webView != null && !webView.customSettings.useHybridComposition) {
webView.setContainerView(flutterView);
}
}
@Override
public void onFlutterViewDetached() {
if (webView != null && !webView.options.useHybridComposition) {
if (webView != null && !webView.customSettings.useHybridComposition) {
webView.setContainerView(null);
}
}

View File

@ -41,7 +41,6 @@ import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebHistoryItem;
import android.webkit.WebMessage;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.widget.HorizontalScrollView;
@ -120,7 +119,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
@Nullable
public InAppWebViewRenderProcessClient inAppWebViewRenderProcessClient;
public JavaScriptBridgeInterface javaScriptBridgeInterface;
public InAppWebViewOptions options;
public InAppWebViewSettings customSettings;
public boolean isLoading = false;
public OkHttpClient httpClient;
public float zoomScale = 1.0f;
@ -165,15 +164,15 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
public InAppWebView(Context context, InAppWebViewFlutterPlugin plugin,
MethodChannel channel, Object id,
@Nullable Integer windowId, InAppWebViewOptions options,
@Nullable Integer windowId, InAppWebViewSettings customSettings,
@Nullable Map<String, Object> contextMenu, View containerView,
List<UserScript> userScripts) {
super(context, containerView, options.useHybridComposition);
super(context, containerView, customSettings.useHybridComposition);
this.plugin = plugin;
this.channel = channel;
this.id = id;
this.windowId = windowId;
this.options = options;
this.customSettings = customSettings;
this.contextMenu = contextMenu;
this.userContentController.addUserOnlyScripts(userScripts);
plugin.activity.registerForContextMenu(this);
@ -203,167 +202,167 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
userContentController.addPluginScript(PrintJS.PRINT_JS_PLUGIN_SCRIPT);
userContentController.addPluginScript(OnWindowBlurEventJS.ON_WINDOW_BLUR_EVENT_JS_PLUGIN_SCRIPT);
userContentController.addPluginScript(OnWindowFocusEventJS.ON_WINDOW_FOCUS_EVENT_JS_PLUGIN_SCRIPT);
if (options.useShouldInterceptAjaxRequest) {
if (customSettings.useShouldInterceptAjaxRequest) {
userContentController.addPluginScript(InterceptAjaxRequestJS.INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT);
}
if (options.useShouldInterceptFetchRequest) {
if (customSettings.useShouldInterceptFetchRequest) {
userContentController.addPluginScript(InterceptFetchRequestJS.INTERCEPT_FETCH_REQUEST_JS_PLUGIN_SCRIPT);
}
if (options.useOnLoadResource) {
if (customSettings.useOnLoadResource) {
userContentController.addPluginScript(OnLoadResourceJS.ON_LOAD_RESOURCE_JS_PLUGIN_SCRIPT);
}
if (!options.useHybridComposition) {
if (!customSettings.useHybridComposition) {
userContentController.addPluginScript(PluginScriptsUtil.CHECK_GLOBAL_KEY_DOWN_EVENT_TO_HIDE_CONTEXT_MENU_JS_PLUGIN_SCRIPT);
}
if (options.useOnDownloadStart)
if (customSettings.useOnDownloadStart)
setDownloadListener(new DownloadStartListener());
WebSettings settings = getSettings();
settings.setJavaScriptEnabled(options.javaScriptEnabled);
settings.setJavaScriptCanOpenWindowsAutomatically(options.javaScriptCanOpenWindowsAutomatically);
settings.setBuiltInZoomControls(options.builtInZoomControls);
settings.setDisplayZoomControls(options.displayZoomControls);
settings.setSupportMultipleWindows(options.supportMultipleWindows);
settings.setJavaScriptEnabled(customSettings.javaScriptEnabled);
settings.setJavaScriptCanOpenWindowsAutomatically(customSettings.javaScriptCanOpenWindowsAutomatically);
settings.setBuiltInZoomControls(customSettings.builtInZoomControls);
settings.setDisplayZoomControls(customSettings.displayZoomControls);
settings.setSupportMultipleWindows(customSettings.supportMultipleWindows);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
settings.setSafeBrowsingEnabled(options.safeBrowsingEnabled);
settings.setSafeBrowsingEnabled(customSettings.safeBrowsingEnabled);
settings.setMediaPlaybackRequiresUserGesture(options.mediaPlaybackRequiresUserGesture);
settings.setMediaPlaybackRequiresUserGesture(customSettings.mediaPlaybackRequiresUserGesture);
settings.setDatabaseEnabled(options.databaseEnabled);
settings.setDomStorageEnabled(options.domStorageEnabled);
settings.setDatabaseEnabled(customSettings.databaseEnabled);
settings.setDomStorageEnabled(customSettings.domStorageEnabled);
if (options.userAgent != null && !options.userAgent.isEmpty())
settings.setUserAgentString(options.userAgent);
if (customSettings.userAgent != null && !customSettings.userAgent.isEmpty())
settings.setUserAgentString(customSettings.userAgent);
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
settings.setUserAgentString(WebSettings.getDefaultUserAgent(getContext()));
if (options.applicationNameForUserAgent != null && !options.applicationNameForUserAgent.isEmpty()) {
if (customSettings.applicationNameForUserAgent != null && !customSettings.applicationNameForUserAgent.isEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
String userAgent = (options.userAgent != null && !options.userAgent.isEmpty()) ? options.userAgent : WebSettings.getDefaultUserAgent(getContext());
String userAgentWithApplicationName = userAgent + " " + options.applicationNameForUserAgent;
String userAgent = (customSettings.userAgent != null && !customSettings.userAgent.isEmpty()) ? customSettings.userAgent : WebSettings.getDefaultUserAgent(getContext());
String userAgentWithApplicationName = userAgent + " " + customSettings.applicationNameForUserAgent;
settings.setUserAgentString(userAgentWithApplicationName);
}
}
if (options.clearCache)
if (customSettings.clearCache)
clearAllCache();
else if (options.clearSessionCache)
else if (customSettings.clearSessionCache)
CookieManager.getInstance().removeSessionCookie();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
CookieManager.getInstance().setAcceptThirdPartyCookies(this, options.thirdPartyCookiesEnabled);
CookieManager.getInstance().setAcceptThirdPartyCookies(this, customSettings.thirdPartyCookiesEnabled);
settings.setLoadWithOverviewMode(options.loadWithOverviewMode);
settings.setUseWideViewPort(options.useWideViewPort);
settings.setSupportZoom(options.supportZoom);
settings.setTextZoom(options.textZoom);
settings.setLoadWithOverviewMode(customSettings.loadWithOverviewMode);
settings.setUseWideViewPort(customSettings.useWideViewPort);
settings.setSupportZoom(customSettings.supportZoom);
settings.setTextZoom(customSettings.textZoom);
setVerticalScrollBarEnabled(!options.disableVerticalScroll && options.verticalScrollBarEnabled);
setHorizontalScrollBarEnabled(!options.disableHorizontalScroll && options.horizontalScrollBarEnabled);
setVerticalScrollBarEnabled(!customSettings.disableVerticalScroll && customSettings.verticalScrollBarEnabled);
setHorizontalScrollBarEnabled(!customSettings.disableHorizontalScroll && customSettings.horizontalScrollBarEnabled);
if (options.transparentBackground)
if (customSettings.transparentBackground)
setBackgroundColor(Color.TRANSPARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && options.mixedContentMode != null)
settings.setMixedContentMode(options.mixedContentMode);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && customSettings.mixedContentMode != null)
settings.setMixedContentMode(customSettings.mixedContentMode);
settings.setAllowContentAccess(options.allowContentAccess);
settings.setAllowFileAccess(options.allowFileAccess);
settings.setAllowFileAccessFromFileURLs(options.allowFileAccessFromFileURLs);
settings.setAllowUniversalAccessFromFileURLs(options.allowUniversalAccessFromFileURLs);
setCacheEnabled(options.cacheEnabled);
if (options.appCachePath != null && !options.appCachePath.isEmpty() && options.cacheEnabled)
settings.setAppCachePath(options.appCachePath);
settings.setBlockNetworkImage(options.blockNetworkImage);
settings.setBlockNetworkLoads(options.blockNetworkLoads);
if (options.cacheMode != null)
settings.setCacheMode(options.cacheMode);
settings.setCursiveFontFamily(options.cursiveFontFamily);
settings.setDefaultFixedFontSize(options.defaultFixedFontSize);
settings.setDefaultFontSize(options.defaultFontSize);
settings.setDefaultTextEncodingName(options.defaultTextEncodingName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && options.disabledActionModeMenuItems != null)
settings.setDisabledActionModeMenuItems(options.disabledActionModeMenuItems);
settings.setFantasyFontFamily(options.fantasyFontFamily);
settings.setFixedFontFamily(options.fixedFontFamily);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && options.forceDark != null)
settings.setForceDark(options.forceDark);
settings.setGeolocationEnabled(options.geolocationEnabled);
if (options.layoutAlgorithm != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && options.layoutAlgorithm.equals(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING)) {
settings.setLayoutAlgorithm(options.layoutAlgorithm);
settings.setAllowContentAccess(customSettings.allowContentAccess);
settings.setAllowFileAccess(customSettings.allowFileAccess);
settings.setAllowFileAccessFromFileURLs(customSettings.allowFileAccessFromFileURLs);
settings.setAllowUniversalAccessFromFileURLs(customSettings.allowUniversalAccessFromFileURLs);
setCacheEnabled(customSettings.cacheEnabled);
if (customSettings.appCachePath != null && !customSettings.appCachePath.isEmpty() && customSettings.cacheEnabled)
settings.setAppCachePath(customSettings.appCachePath);
settings.setBlockNetworkImage(customSettings.blockNetworkImage);
settings.setBlockNetworkLoads(customSettings.blockNetworkLoads);
if (customSettings.cacheMode != null)
settings.setCacheMode(customSettings.cacheMode);
settings.setCursiveFontFamily(customSettings.cursiveFontFamily);
settings.setDefaultFixedFontSize(customSettings.defaultFixedFontSize);
settings.setDefaultFontSize(customSettings.defaultFontSize);
settings.setDefaultTextEncodingName(customSettings.defaultTextEncodingName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && customSettings.disabledActionModeMenuItems != null)
settings.setDisabledActionModeMenuItems(customSettings.disabledActionModeMenuItems);
settings.setFantasyFontFamily(customSettings.fantasyFontFamily);
settings.setFixedFontFamily(customSettings.fixedFontFamily);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && customSettings.forceDark != null)
settings.setForceDark(customSettings.forceDark);
settings.setGeolocationEnabled(customSettings.geolocationEnabled);
if (customSettings.layoutAlgorithm != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && customSettings.layoutAlgorithm.equals(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING)) {
settings.setLayoutAlgorithm(customSettings.layoutAlgorithm);
} else {
settings.setLayoutAlgorithm(options.layoutAlgorithm);
settings.setLayoutAlgorithm(customSettings.layoutAlgorithm);
}
}
settings.setLoadsImagesAutomatically(options.loadsImagesAutomatically);
settings.setMinimumFontSize(options.minimumFontSize);
settings.setMinimumLogicalFontSize(options.minimumLogicalFontSize);
setInitialScale(options.initialScale);
settings.setNeedInitialFocus(options.needInitialFocus);
settings.setLoadsImagesAutomatically(customSettings.loadsImagesAutomatically);
settings.setMinimumFontSize(customSettings.minimumFontSize);
settings.setMinimumLogicalFontSize(customSettings.minimumLogicalFontSize);
setInitialScale(customSettings.initialScale);
settings.setNeedInitialFocus(customSettings.needInitialFocus);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
settings.setOffscreenPreRaster(options.offscreenPreRaster);
settings.setSansSerifFontFamily(options.sansSerifFontFamily);
settings.setSerifFontFamily(options.serifFontFamily);
settings.setStandardFontFamily(options.standardFontFamily);
if (options.preferredContentMode != null &&
options.preferredContentMode == PreferredContentModeOptionType.DESKTOP.toValue()) {
settings.setOffscreenPreRaster(customSettings.offscreenPreRaster);
settings.setSansSerifFontFamily(customSettings.sansSerifFontFamily);
settings.setSerifFontFamily(customSettings.serifFontFamily);
settings.setStandardFontFamily(customSettings.standardFontFamily);
if (customSettings.preferredContentMode != null &&
customSettings.preferredContentMode == PreferredContentModeOptionType.DESKTOP.toValue()) {
setDesktopMode(true);
}
settings.setSaveFormData(options.saveFormData);
if (options.incognito)
settings.setSaveFormData(customSettings.saveFormData);
if (customSettings.incognito)
setIncognito(true);
if (options.hardwareAcceleration)
if (customSettings.hardwareAcceleration)
setLayerType(View.LAYER_TYPE_HARDWARE, null);
else
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
if (options.regexToCancelSubFramesLoading != null) {
regexToCancelSubFramesLoadingCompiled = Pattern.compile(options.regexToCancelSubFramesLoading);
if (customSettings.regexToCancelSubFramesLoading != null) {
regexToCancelSubFramesLoadingCompiled = Pattern.compile(customSettings.regexToCancelSubFramesLoading);
}
setScrollBarStyle(options.scrollBarStyle);
if (options.scrollBarDefaultDelayBeforeFade != null) {
setScrollBarDefaultDelayBeforeFade(options.scrollBarDefaultDelayBeforeFade);
setScrollBarStyle(customSettings.scrollBarStyle);
if (customSettings.scrollBarDefaultDelayBeforeFade != null) {
setScrollBarDefaultDelayBeforeFade(customSettings.scrollBarDefaultDelayBeforeFade);
} else {
options.scrollBarDefaultDelayBeforeFade = getScrollBarDefaultDelayBeforeFade();
customSettings.scrollBarDefaultDelayBeforeFade = getScrollBarDefaultDelayBeforeFade();
}
setScrollbarFadingEnabled(options.scrollbarFadingEnabled);
if (options.scrollBarFadeDuration != null) {
setScrollBarFadeDuration(options.scrollBarFadeDuration);
setScrollbarFadingEnabled(customSettings.scrollbarFadingEnabled);
if (customSettings.scrollBarFadeDuration != null) {
setScrollBarFadeDuration(customSettings.scrollBarFadeDuration);
} else {
options.scrollBarFadeDuration = getScrollBarFadeDuration();
customSettings.scrollBarFadeDuration = getScrollBarFadeDuration();
}
setVerticalScrollbarPosition(options.verticalScrollbarPosition);
setVerticalScrollbarPosition(customSettings.verticalScrollbarPosition);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (options.verticalScrollbarThumbColor != null)
setVerticalScrollbarThumbDrawable(new ColorDrawable(Color.parseColor(options.verticalScrollbarThumbColor)));
if (options.verticalScrollbarTrackColor != null)
setVerticalScrollbarTrackDrawable(new ColorDrawable(Color.parseColor(options.verticalScrollbarTrackColor)));
if (options.horizontalScrollbarThumbColor != null)
setHorizontalScrollbarThumbDrawable(new ColorDrawable(Color.parseColor(options.horizontalScrollbarThumbColor)));
if (options.horizontalScrollbarTrackColor != null)
setHorizontalScrollbarTrackDrawable(new ColorDrawable(Color.parseColor(options.horizontalScrollbarTrackColor)));
if (customSettings.verticalScrollbarThumbColor != null)
setVerticalScrollbarThumbDrawable(new ColorDrawable(Color.parseColor(customSettings.verticalScrollbarThumbColor)));
if (customSettings.verticalScrollbarTrackColor != null)
setVerticalScrollbarTrackDrawable(new ColorDrawable(Color.parseColor(customSettings.verticalScrollbarTrackColor)));
if (customSettings.horizontalScrollbarThumbColor != null)
setHorizontalScrollbarThumbDrawable(new ColorDrawable(Color.parseColor(customSettings.horizontalScrollbarThumbColor)));
if (customSettings.horizontalScrollbarTrackColor != null)
setHorizontalScrollbarTrackDrawable(new ColorDrawable(Color.parseColor(customSettings.horizontalScrollbarTrackColor)));
}
setOverScrollMode(options.overScrollMode);
if (options.networkAvailable != null) {
setNetworkAvailable(options.networkAvailable);
setOverScrollMode(customSettings.overScrollMode);
if (customSettings.networkAvailable != null) {
setNetworkAvailable(customSettings.networkAvailable);
}
if (options.rendererPriorityPolicy != null && !options.rendererPriorityPolicy.isEmpty() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (customSettings.rendererPriorityPolicy != null && !customSettings.rendererPriorityPolicy.isEmpty() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setRendererPriorityPolicy(
(int) options.rendererPriorityPolicy.get("rendererRequestedPriority"),
(boolean) options.rendererPriorityPolicy.get("waivedWhenNotVisible"));
} else if ((options.rendererPriorityPolicy == null || (options.rendererPriorityPolicy != null && options.rendererPriorityPolicy.isEmpty())) &&
(int) customSettings.rendererPriorityPolicy.get("rendererRequestedPriority"),
(boolean) customSettings.rendererPriorityPolicy.get("waivedWhenNotVisible"));
} else if ((customSettings.rendererPriorityPolicy == null || (customSettings.rendererPriorityPolicy != null && customSettings.rendererPriorityPolicy.isEmpty())) &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
options.rendererPriorityPolicy.put("rendererRequestedPriority", getRendererRequestedPriority());
options.rendererPriorityPolicy.put("waivedWhenNotVisible", getRendererPriorityWaivedWhenNotVisible());
customSettings.rendererPriorityPolicy.put("rendererRequestedPriority", getRendererRequestedPriority());
customSettings.rendererPriorityPolicy.put("waivedWhenNotVisible", getRendererPriorityWaivedWhenNotVisible());
}
contentBlockerHandler.getRuleList().clear();
for (Map<String, Map<String, Object>> contentBlocker : options.contentBlockers) {
for (Map<String, Map<String, Object>> contentBlocker : customSettings.contentBlockers) {
// compile ContentBlockerTrigger urlFilter
ContentBlockerTrigger trigger = ContentBlockerTrigger.fromMap(contentBlocker.get("trigger"));
ContentBlockerAction action = ContentBlockerAction.fromMap(contentBlocker.get("action"));
@ -405,7 +404,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && !options.useHybridComposition) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && !customSettings.useHybridComposition) {
checkContextMenuShouldBeClosedTask = new Runnable() {
@Override
public void run() {
@ -439,9 +438,9 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
checkScrollStoppedTask.run();
}
if (options.disableHorizontalScroll && options.disableVerticalScroll) {
if (customSettings.disableHorizontalScroll && customSettings.disableVerticalScroll) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
} else if (options.disableHorizontalScroll || options.disableVerticalScroll) {
} else if (customSettings.disableHorizontalScroll || customSettings.disableVerticalScroll) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
// save the x
@ -453,7 +452,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
if (options.disableHorizontalScroll) {
if (customSettings.disableHorizontalScroll) {
// set x so that it doesn't move
event.setLocation(m_downX, event.getY());
} else {
@ -638,94 +637,94 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
});
}
public void setOptions(InAppWebViewOptions newOptions, HashMap<String, Object> newOptionsMap) {
public void setSettings(InAppWebViewSettings newSettings, HashMap<String, Object> newSettingsMap) {
WebSettings settings = getSettings();
if (newOptionsMap.get("javaScriptEnabled") != null && options.javaScriptEnabled != newOptions.javaScriptEnabled)
settings.setJavaScriptEnabled(newOptions.javaScriptEnabled);
if (newSettingsMap.get("javaScriptEnabled") != null && customSettings.javaScriptEnabled != newSettings.javaScriptEnabled)
settings.setJavaScriptEnabled(newSettings.javaScriptEnabled);
if (newOptionsMap.get("useShouldInterceptAjaxRequest") != null && options.useShouldInterceptAjaxRequest != newOptions.useShouldInterceptAjaxRequest) {
if (newSettingsMap.get("useShouldInterceptAjaxRequest") != null && customSettings.useShouldInterceptAjaxRequest != newSettings.useShouldInterceptAjaxRequest) {
enablePluginScriptAtRuntime(
InterceptAjaxRequestJS.FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE,
newOptions.useShouldInterceptAjaxRequest,
newSettings.useShouldInterceptAjaxRequest,
InterceptAjaxRequestJS.INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT
);
}
if (newOptionsMap.get("useShouldInterceptFetchRequest") != null && options.useShouldInterceptFetchRequest != newOptions.useShouldInterceptFetchRequest) {
if (newSettingsMap.get("useShouldInterceptFetchRequest") != null && customSettings.useShouldInterceptFetchRequest != newSettings.useShouldInterceptFetchRequest) {
enablePluginScriptAtRuntime(
InterceptFetchRequestJS.FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_FETCH_REQUEST_JS_SOURCE,
newOptions.useShouldInterceptFetchRequest,
newSettings.useShouldInterceptFetchRequest,
InterceptFetchRequestJS.INTERCEPT_FETCH_REQUEST_JS_PLUGIN_SCRIPT
);
}
if (newOptionsMap.get("useOnLoadResource") != null && options.useOnLoadResource != newOptions.useOnLoadResource) {
if (newSettingsMap.get("useOnLoadResource") != null && customSettings.useOnLoadResource != newSettings.useOnLoadResource) {
enablePluginScriptAtRuntime(
OnLoadResourceJS.FLAG_VARIABLE_FOR_ON_LOAD_RESOURCE_JS_SOURCE,
newOptions.useOnLoadResource,
newSettings.useOnLoadResource,
OnLoadResourceJS.ON_LOAD_RESOURCE_JS_PLUGIN_SCRIPT
);
}
if (newOptionsMap.get("javaScriptCanOpenWindowsAutomatically") != null && options.javaScriptCanOpenWindowsAutomatically != newOptions.javaScriptCanOpenWindowsAutomatically)
settings.setJavaScriptCanOpenWindowsAutomatically(newOptions.javaScriptCanOpenWindowsAutomatically);
if (newSettingsMap.get("javaScriptCanOpenWindowsAutomatically") != null && customSettings.javaScriptCanOpenWindowsAutomatically != newSettings.javaScriptCanOpenWindowsAutomatically)
settings.setJavaScriptCanOpenWindowsAutomatically(newSettings.javaScriptCanOpenWindowsAutomatically);
if (newOptionsMap.get("builtInZoomControls") != null && options.builtInZoomControls != newOptions.builtInZoomControls)
settings.setBuiltInZoomControls(newOptions.builtInZoomControls);
if (newSettingsMap.get("builtInZoomControls") != null && customSettings.builtInZoomControls != newSettings.builtInZoomControls)
settings.setBuiltInZoomControls(newSettings.builtInZoomControls);
if (newOptionsMap.get("displayZoomControls") != null && options.displayZoomControls != newOptions.displayZoomControls)
settings.setDisplayZoomControls(newOptions.displayZoomControls);
if (newSettingsMap.get("displayZoomControls") != null && customSettings.displayZoomControls != newSettings.displayZoomControls)
settings.setDisplayZoomControls(newSettings.displayZoomControls);
if (newOptionsMap.get("safeBrowsingEnabled") != null && options.safeBrowsingEnabled != newOptions.safeBrowsingEnabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
settings.setSafeBrowsingEnabled(newOptions.safeBrowsingEnabled);
if (newSettingsMap.get("safeBrowsingEnabled") != null && customSettings.safeBrowsingEnabled != newSettings.safeBrowsingEnabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
settings.setSafeBrowsingEnabled(newSettings.safeBrowsingEnabled);
if (newOptionsMap.get("mediaPlaybackRequiresUserGesture") != null && options.mediaPlaybackRequiresUserGesture != newOptions.mediaPlaybackRequiresUserGesture)
settings.setMediaPlaybackRequiresUserGesture(newOptions.mediaPlaybackRequiresUserGesture);
if (newSettingsMap.get("mediaPlaybackRequiresUserGesture") != null && customSettings.mediaPlaybackRequiresUserGesture != newSettings.mediaPlaybackRequiresUserGesture)
settings.setMediaPlaybackRequiresUserGesture(newSettings.mediaPlaybackRequiresUserGesture);
if (newOptionsMap.get("databaseEnabled") != null && options.databaseEnabled != newOptions.databaseEnabled)
settings.setDatabaseEnabled(newOptions.databaseEnabled);
if (newSettingsMap.get("databaseEnabled") != null && customSettings.databaseEnabled != newSettings.databaseEnabled)
settings.setDatabaseEnabled(newSettings.databaseEnabled);
if (newOptionsMap.get("domStorageEnabled") != null && options.domStorageEnabled != newOptions.domStorageEnabled)
settings.setDomStorageEnabled(newOptions.domStorageEnabled);
if (newSettingsMap.get("domStorageEnabled") != null && customSettings.domStorageEnabled != newSettings.domStorageEnabled)
settings.setDomStorageEnabled(newSettings.domStorageEnabled);
if (newOptionsMap.get("userAgent") != null && !options.userAgent.equals(newOptions.userAgent) && !newOptions.userAgent.isEmpty())
settings.setUserAgentString(newOptions.userAgent);
if (newSettingsMap.get("userAgent") != null && !customSettings.userAgent.equals(newSettings.userAgent) && !newSettings.userAgent.isEmpty())
settings.setUserAgentString(newSettings.userAgent);
if (newOptionsMap.get("applicationNameForUserAgent") != null && !options.applicationNameForUserAgent.equals(newOptions.applicationNameForUserAgent) && !newOptions.applicationNameForUserAgent.isEmpty()) {
if (newSettingsMap.get("applicationNameForUserAgent") != null && !customSettings.applicationNameForUserAgent.equals(newSettings.applicationNameForUserAgent) && !newSettings.applicationNameForUserAgent.isEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
String userAgent = (newOptions.userAgent != null && !newOptions.userAgent.isEmpty()) ? newOptions.userAgent : WebSettings.getDefaultUserAgent(getContext());
String userAgentWithApplicationName = userAgent + " " + options.applicationNameForUserAgent;
String userAgent = (newSettings.userAgent != null && !newSettings.userAgent.isEmpty()) ? newSettings.userAgent : WebSettings.getDefaultUserAgent(getContext());
String userAgentWithApplicationName = userAgent + " " + customSettings.applicationNameForUserAgent;
settings.setUserAgentString(userAgentWithApplicationName);
}
}
if (newOptionsMap.get("clearCache") != null && newOptions.clearCache)
if (newSettingsMap.get("clearCache") != null && newSettings.clearCache)
clearAllCache();
else if (newOptionsMap.get("clearSessionCache") != null && newOptions.clearSessionCache)
else if (newSettingsMap.get("clearSessionCache") != null && newSettings.clearSessionCache)
CookieManager.getInstance().removeSessionCookie();
if (newOptionsMap.get("thirdPartyCookiesEnabled") != null && options.thirdPartyCookiesEnabled != newOptions.thirdPartyCookiesEnabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
CookieManager.getInstance().setAcceptThirdPartyCookies(this, newOptions.thirdPartyCookiesEnabled);
if (newSettingsMap.get("thirdPartyCookiesEnabled") != null && customSettings.thirdPartyCookiesEnabled != newSettings.thirdPartyCookiesEnabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
CookieManager.getInstance().setAcceptThirdPartyCookies(this, newSettings.thirdPartyCookiesEnabled);
if (newOptionsMap.get("useWideViewPort") != null && options.useWideViewPort != newOptions.useWideViewPort)
settings.setUseWideViewPort(newOptions.useWideViewPort);
if (newSettingsMap.get("useWideViewPort") != null && customSettings.useWideViewPort != newSettings.useWideViewPort)
settings.setUseWideViewPort(newSettings.useWideViewPort);
if (newOptionsMap.get("supportZoom") != null && options.supportZoom != newOptions.supportZoom)
settings.setSupportZoom(newOptions.supportZoom);
if (newSettingsMap.get("supportZoom") != null && customSettings.supportZoom != newSettings.supportZoom)
settings.setSupportZoom(newSettings.supportZoom);
if (newOptionsMap.get("textZoom") != null && !options.textZoom.equals(newOptions.textZoom))
settings.setTextZoom(newOptions.textZoom);
if (newSettingsMap.get("textZoom") != null && !customSettings.textZoom.equals(newSettings.textZoom))
settings.setTextZoom(newSettings.textZoom);
if (newOptionsMap.get("verticalScrollBarEnabled") != null && options.verticalScrollBarEnabled != newOptions.verticalScrollBarEnabled)
setVerticalScrollBarEnabled(newOptions.verticalScrollBarEnabled);
if (newSettingsMap.get("verticalScrollBarEnabled") != null && customSettings.verticalScrollBarEnabled != newSettings.verticalScrollBarEnabled)
setVerticalScrollBarEnabled(newSettings.verticalScrollBarEnabled);
if (newOptionsMap.get("horizontalScrollBarEnabled") != null && options.horizontalScrollBarEnabled != newOptions.horizontalScrollBarEnabled)
setHorizontalScrollBarEnabled(newOptions.horizontalScrollBarEnabled);
if (newSettingsMap.get("horizontalScrollBarEnabled") != null && customSettings.horizontalScrollBarEnabled != newSettings.horizontalScrollBarEnabled)
setHorizontalScrollBarEnabled(newSettings.horizontalScrollBarEnabled);
if (newOptionsMap.get("transparentBackground") != null && options.transparentBackground != newOptions.transparentBackground) {
if (newOptions.transparentBackground) {
if (newSettingsMap.get("transparentBackground") != null && customSettings.transparentBackground != newSettings.transparentBackground) {
if (newSettings.transparentBackground) {
setBackgroundColor(Color.TRANSPARENT);
} else {
setBackgroundColor(Color.parseColor("#FFFFFF"));
@ -733,118 +732,118 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
if (newOptionsMap.get("mixedContentMode") != null && (options.mixedContentMode == null || !options.mixedContentMode.equals(newOptions.mixedContentMode)))
settings.setMixedContentMode(newOptions.mixedContentMode);
if (newSettingsMap.get("mixedContentMode") != null && (customSettings.mixedContentMode == null || !customSettings.mixedContentMode.equals(newSettings.mixedContentMode)))
settings.setMixedContentMode(newSettings.mixedContentMode);
if (newOptionsMap.get("supportMultipleWindows") != null && options.supportMultipleWindows != newOptions.supportMultipleWindows)
settings.setSupportMultipleWindows(newOptions.supportMultipleWindows);
if (newSettingsMap.get("supportMultipleWindows") != null && customSettings.supportMultipleWindows != newSettings.supportMultipleWindows)
settings.setSupportMultipleWindows(newSettings.supportMultipleWindows);
if (newOptionsMap.get("useOnDownloadStart") != null && options.useOnDownloadStart != newOptions.useOnDownloadStart) {
if (newOptions.useOnDownloadStart) {
if (newSettingsMap.get("useOnDownloadStart") != null && customSettings.useOnDownloadStart != newSettings.useOnDownloadStart) {
if (newSettings.useOnDownloadStart) {
setDownloadListener(new DownloadStartListener());
} else {
setDownloadListener(null);
}
}
if (newOptionsMap.get("allowContentAccess") != null && options.allowContentAccess != newOptions.allowContentAccess)
settings.setAllowContentAccess(newOptions.allowContentAccess);
if (newSettingsMap.get("allowContentAccess") != null && customSettings.allowContentAccess != newSettings.allowContentAccess)
settings.setAllowContentAccess(newSettings.allowContentAccess);
if (newOptionsMap.get("allowFileAccess") != null && options.allowFileAccess != newOptions.allowFileAccess)
settings.setAllowFileAccess(newOptions.allowFileAccess);
if (newSettingsMap.get("allowFileAccess") != null && customSettings.allowFileAccess != newSettings.allowFileAccess)
settings.setAllowFileAccess(newSettings.allowFileAccess);
if (newOptionsMap.get("allowFileAccessFromFileURLs") != null && options.allowFileAccessFromFileURLs != newOptions.allowFileAccessFromFileURLs)
settings.setAllowFileAccessFromFileURLs(newOptions.allowFileAccessFromFileURLs);
if (newSettingsMap.get("allowFileAccessFromFileURLs") != null && customSettings.allowFileAccessFromFileURLs != newSettings.allowFileAccessFromFileURLs)
settings.setAllowFileAccessFromFileURLs(newSettings.allowFileAccessFromFileURLs);
if (newOptionsMap.get("allowUniversalAccessFromFileURLs") != null && options.allowUniversalAccessFromFileURLs != newOptions.allowUniversalAccessFromFileURLs)
settings.setAllowUniversalAccessFromFileURLs(newOptions.allowUniversalAccessFromFileURLs);
if (newSettingsMap.get("allowUniversalAccessFromFileURLs") != null && customSettings.allowUniversalAccessFromFileURLs != newSettings.allowUniversalAccessFromFileURLs)
settings.setAllowUniversalAccessFromFileURLs(newSettings.allowUniversalAccessFromFileURLs);
if (newOptionsMap.get("cacheEnabled") != null && options.cacheEnabled != newOptions.cacheEnabled)
setCacheEnabled(newOptions.cacheEnabled);
if (newSettingsMap.get("cacheEnabled") != null && customSettings.cacheEnabled != newSettings.cacheEnabled)
setCacheEnabled(newSettings.cacheEnabled);
if (newOptionsMap.get("appCachePath") != null && (options.appCachePath == null || !options.appCachePath.equals(newOptions.appCachePath)))
settings.setAppCachePath(newOptions.appCachePath);
if (newSettingsMap.get("appCachePath") != null && (customSettings.appCachePath == null || !customSettings.appCachePath.equals(newSettings.appCachePath)))
settings.setAppCachePath(newSettings.appCachePath);
if (newOptionsMap.get("blockNetworkImage") != null && options.blockNetworkImage != newOptions.blockNetworkImage)
settings.setBlockNetworkImage(newOptions.blockNetworkImage);
if (newSettingsMap.get("blockNetworkImage") != null && customSettings.blockNetworkImage != newSettings.blockNetworkImage)
settings.setBlockNetworkImage(newSettings.blockNetworkImage);
if (newOptionsMap.get("blockNetworkLoads") != null && options.blockNetworkLoads != newOptions.blockNetworkLoads)
settings.setBlockNetworkLoads(newOptions.blockNetworkLoads);
if (newSettingsMap.get("blockNetworkLoads") != null && customSettings.blockNetworkLoads != newSettings.blockNetworkLoads)
settings.setBlockNetworkLoads(newSettings.blockNetworkLoads);
if (newOptionsMap.get("cacheMode") != null && !options.cacheMode.equals(newOptions.cacheMode))
settings.setCacheMode(newOptions.cacheMode);
if (newSettingsMap.get("cacheMode") != null && !customSettings.cacheMode.equals(newSettings.cacheMode))
settings.setCacheMode(newSettings.cacheMode);
if (newOptionsMap.get("cursiveFontFamily") != null && !options.cursiveFontFamily.equals(newOptions.cursiveFontFamily))
settings.setCursiveFontFamily(newOptions.cursiveFontFamily);
if (newSettingsMap.get("cursiveFontFamily") != null && !customSettings.cursiveFontFamily.equals(newSettings.cursiveFontFamily))
settings.setCursiveFontFamily(newSettings.cursiveFontFamily);
if (newOptionsMap.get("defaultFixedFontSize") != null && !options.defaultFixedFontSize.equals(newOptions.defaultFixedFontSize))
settings.setDefaultFixedFontSize(newOptions.defaultFixedFontSize);
if (newSettingsMap.get("defaultFixedFontSize") != null && !customSettings.defaultFixedFontSize.equals(newSettings.defaultFixedFontSize))
settings.setDefaultFixedFontSize(newSettings.defaultFixedFontSize);
if (newOptionsMap.get("defaultFontSize") != null && !options.defaultFontSize.equals(newOptions.defaultFontSize))
settings.setDefaultFontSize(newOptions.defaultFontSize);
if (newSettingsMap.get("defaultFontSize") != null && !customSettings.defaultFontSize.equals(newSettings.defaultFontSize))
settings.setDefaultFontSize(newSettings.defaultFontSize);
if (newOptionsMap.get("defaultTextEncodingName") != null && !options.defaultTextEncodingName.equals(newOptions.defaultTextEncodingName))
settings.setDefaultTextEncodingName(newOptions.defaultTextEncodingName);
if (newSettingsMap.get("defaultTextEncodingName") != null && !customSettings.defaultTextEncodingName.equals(newSettings.defaultTextEncodingName))
settings.setDefaultTextEncodingName(newSettings.defaultTextEncodingName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
if (newOptionsMap.get("disabledActionModeMenuItems") != null && (options.disabledActionModeMenuItems == null ||
!options.disabledActionModeMenuItems.equals(newOptions.disabledActionModeMenuItems)))
settings.setDisabledActionModeMenuItems(newOptions.disabledActionModeMenuItems);
if (newSettingsMap.get("disabledActionModeMenuItems") != null && (customSettings.disabledActionModeMenuItems == null ||
!customSettings.disabledActionModeMenuItems.equals(newSettings.disabledActionModeMenuItems)))
settings.setDisabledActionModeMenuItems(newSettings.disabledActionModeMenuItems);
if (newOptionsMap.get("fantasyFontFamily") != null && !options.fantasyFontFamily.equals(newOptions.fantasyFontFamily))
settings.setFantasyFontFamily(newOptions.fantasyFontFamily);
if (newSettingsMap.get("fantasyFontFamily") != null && !customSettings.fantasyFontFamily.equals(newSettings.fantasyFontFamily))
settings.setFantasyFontFamily(newSettings.fantasyFontFamily);
if (newOptionsMap.get("fixedFontFamily") != null && !options.fixedFontFamily.equals(newOptions.fixedFontFamily))
settings.setFixedFontFamily(newOptions.fixedFontFamily);
if (newSettingsMap.get("fixedFontFamily") != null && !customSettings.fixedFontFamily.equals(newSettings.fixedFontFamily))
settings.setFixedFontFamily(newSettings.fixedFontFamily);
if (newOptionsMap.get("forceDark") != null && !options.forceDark.equals(newOptions.forceDark))
if (newSettingsMap.get("forceDark") != null && !customSettings.forceDark.equals(newSettings.forceDark))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
settings.setForceDark(newOptions.forceDark);
settings.setForceDark(newSettings.forceDark);
if (newOptionsMap.get("geolocationEnabled") != null && options.geolocationEnabled != newOptions.geolocationEnabled)
settings.setGeolocationEnabled(newOptions.geolocationEnabled);
if (newSettingsMap.get("geolocationEnabled") != null && customSettings.geolocationEnabled != newSettings.geolocationEnabled)
settings.setGeolocationEnabled(newSettings.geolocationEnabled);
if (newOptionsMap.get("layoutAlgorithm") != null && options.layoutAlgorithm != newOptions.layoutAlgorithm) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && newOptions.layoutAlgorithm.equals(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING)) {
settings.setLayoutAlgorithm(newOptions.layoutAlgorithm);
if (newSettingsMap.get("layoutAlgorithm") != null && customSettings.layoutAlgorithm != newSettings.layoutAlgorithm) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && newSettings.layoutAlgorithm.equals(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING)) {
settings.setLayoutAlgorithm(newSettings.layoutAlgorithm);
} else {
settings.setLayoutAlgorithm(newOptions.layoutAlgorithm);
settings.setLayoutAlgorithm(newSettings.layoutAlgorithm);
}
}
if (newOptionsMap.get("loadWithOverviewMode") != null && options.loadWithOverviewMode != newOptions.loadWithOverviewMode)
settings.setLoadWithOverviewMode(newOptions.loadWithOverviewMode);
if (newSettingsMap.get("loadWithOverviewMode") != null && customSettings.loadWithOverviewMode != newSettings.loadWithOverviewMode)
settings.setLoadWithOverviewMode(newSettings.loadWithOverviewMode);
if (newOptionsMap.get("loadsImagesAutomatically") != null && options.loadsImagesAutomatically != newOptions.loadsImagesAutomatically)
settings.setLoadsImagesAutomatically(newOptions.loadsImagesAutomatically);
if (newSettingsMap.get("loadsImagesAutomatically") != null && customSettings.loadsImagesAutomatically != newSettings.loadsImagesAutomatically)
settings.setLoadsImagesAutomatically(newSettings.loadsImagesAutomatically);
if (newOptionsMap.get("minimumFontSize") != null && !options.minimumFontSize.equals(newOptions.minimumFontSize))
settings.setMinimumFontSize(newOptions.minimumFontSize);
if (newSettingsMap.get("minimumFontSize") != null && !customSettings.minimumFontSize.equals(newSettings.minimumFontSize))
settings.setMinimumFontSize(newSettings.minimumFontSize);
if (newOptionsMap.get("minimumLogicalFontSize") != null && !options.minimumLogicalFontSize.equals(newOptions.minimumLogicalFontSize))
settings.setMinimumLogicalFontSize(newOptions.minimumLogicalFontSize);
if (newSettingsMap.get("minimumLogicalFontSize") != null && !customSettings.minimumLogicalFontSize.equals(newSettings.minimumLogicalFontSize))
settings.setMinimumLogicalFontSize(newSettings.minimumLogicalFontSize);
if (newOptionsMap.get("initialScale") != null && !options.initialScale.equals(newOptions.initialScale))
setInitialScale(newOptions.initialScale);
if (newSettingsMap.get("initialScale") != null && !customSettings.initialScale.equals(newSettings.initialScale))
setInitialScale(newSettings.initialScale);
if (newOptionsMap.get("needInitialFocus") != null && options.needInitialFocus != newOptions.needInitialFocus)
settings.setNeedInitialFocus(newOptions.needInitialFocus);
if (newSettingsMap.get("needInitialFocus") != null && customSettings.needInitialFocus != newSettings.needInitialFocus)
settings.setNeedInitialFocus(newSettings.needInitialFocus);
if (newOptionsMap.get("offscreenPreRaster") != null && options.offscreenPreRaster != newOptions.offscreenPreRaster)
if (newSettingsMap.get("offscreenPreRaster") != null && customSettings.offscreenPreRaster != newSettings.offscreenPreRaster)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
settings.setOffscreenPreRaster(newOptions.offscreenPreRaster);
settings.setOffscreenPreRaster(newSettings.offscreenPreRaster);
if (newOptionsMap.get("sansSerifFontFamily") != null && !options.sansSerifFontFamily.equals(newOptions.sansSerifFontFamily))
settings.setSansSerifFontFamily(newOptions.sansSerifFontFamily);
if (newSettingsMap.get("sansSerifFontFamily") != null && !customSettings.sansSerifFontFamily.equals(newSettings.sansSerifFontFamily))
settings.setSansSerifFontFamily(newSettings.sansSerifFontFamily);
if (newOptionsMap.get("serifFontFamily") != null && !options.serifFontFamily.equals(newOptions.serifFontFamily))
settings.setSerifFontFamily(newOptions.serifFontFamily);
if (newSettingsMap.get("serifFontFamily") != null && !customSettings.serifFontFamily.equals(newSettings.serifFontFamily))
settings.setSerifFontFamily(newSettings.serifFontFamily);
if (newOptionsMap.get("standardFontFamily") != null && !options.standardFontFamily.equals(newOptions.standardFontFamily))
settings.setStandardFontFamily(newOptions.standardFontFamily);
if (newSettingsMap.get("standardFontFamily") != null && !customSettings.standardFontFamily.equals(newSettings.standardFontFamily))
settings.setStandardFontFamily(newSettings.standardFontFamily);
if (newOptionsMap.get("preferredContentMode") != null && !options.preferredContentMode.equals(newOptions.preferredContentMode)) {
switch (fromValue(newOptions.preferredContentMode)) {
if (newSettingsMap.get("preferredContentMode") != null && !customSettings.preferredContentMode.equals(newSettings.preferredContentMode)) {
switch (fromValue(newSettings.preferredContentMode)) {
case DESKTOP:
setDesktopMode(true);
break;
@ -855,30 +854,30 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
}
}
if (newOptionsMap.get("saveFormData") != null && options.saveFormData != newOptions.saveFormData)
settings.setSaveFormData(newOptions.saveFormData);
if (newSettingsMap.get("saveFormData") != null && customSettings.saveFormData != newSettings.saveFormData)
settings.setSaveFormData(newSettings.saveFormData);
if (newOptionsMap.get("incognito") != null && options.incognito != newOptions.incognito)
setIncognito(newOptions.incognito);
if (newSettingsMap.get("incognito") != null && customSettings.incognito != newSettings.incognito)
setIncognito(newSettings.incognito);
if (newOptionsMap.get("hardwareAcceleration") != null && options.hardwareAcceleration != newOptions.hardwareAcceleration) {
if (newOptions.hardwareAcceleration)
if (newSettingsMap.get("hardwareAcceleration") != null && customSettings.hardwareAcceleration != newSettings.hardwareAcceleration) {
if (newSettings.hardwareAcceleration)
setLayerType(View.LAYER_TYPE_HARDWARE, null);
else
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
if (newOptionsMap.get("regexToCancelSubFramesLoading") != null && (options.regexToCancelSubFramesLoading == null ||
!options.regexToCancelSubFramesLoading.equals(newOptions.regexToCancelSubFramesLoading))) {
if (newOptions.regexToCancelSubFramesLoading == null)
if (newSettingsMap.get("regexToCancelSubFramesLoading") != null && (customSettings.regexToCancelSubFramesLoading == null ||
!customSettings.regexToCancelSubFramesLoading.equals(newSettings.regexToCancelSubFramesLoading))) {
if (newSettings.regexToCancelSubFramesLoading == null)
regexToCancelSubFramesLoadingCompiled = null;
else
regexToCancelSubFramesLoadingCompiled = Pattern.compile(options.regexToCancelSubFramesLoading);
regexToCancelSubFramesLoadingCompiled = Pattern.compile(customSettings.regexToCancelSubFramesLoading);
}
if (newOptions.contentBlockers != null) {
if (newSettings.contentBlockers != null) {
contentBlockerHandler.getRuleList().clear();
for (Map<String, Map<String, Object>> contentBlocker : newOptions.contentBlockers) {
for (Map<String, Map<String, Object>> contentBlocker : newSettings.contentBlockers) {
// compile ContentBlockerTrigger urlFilter
ContentBlockerTrigger trigger = ContentBlockerTrigger.fromMap(contentBlocker.get("trigger"));
ContentBlockerAction action = ContentBlockerAction.fromMap(contentBlocker.get("action"));
@ -886,63 +885,63 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
}
}
if (newOptionsMap.get("scrollBarStyle") != null && !options.scrollBarStyle.equals(newOptions.scrollBarStyle))
setScrollBarStyle(newOptions.scrollBarStyle);
if (newSettingsMap.get("scrollBarStyle") != null && !customSettings.scrollBarStyle.equals(newSettings.scrollBarStyle))
setScrollBarStyle(newSettings.scrollBarStyle);
if (newOptionsMap.get("scrollBarDefaultDelayBeforeFade") != null && (options.scrollBarDefaultDelayBeforeFade == null ||
!options.scrollBarDefaultDelayBeforeFade.equals(newOptions.scrollBarDefaultDelayBeforeFade)))
setScrollBarDefaultDelayBeforeFade(newOptions.scrollBarDefaultDelayBeforeFade);
if (newSettingsMap.get("scrollBarDefaultDelayBeforeFade") != null && (customSettings.scrollBarDefaultDelayBeforeFade == null ||
!customSettings.scrollBarDefaultDelayBeforeFade.equals(newSettings.scrollBarDefaultDelayBeforeFade)))
setScrollBarDefaultDelayBeforeFade(newSettings.scrollBarDefaultDelayBeforeFade);
if (newOptionsMap.get("scrollbarFadingEnabled") != null && !options.scrollbarFadingEnabled.equals(newOptions.scrollbarFadingEnabled))
setScrollbarFadingEnabled(newOptions.scrollbarFadingEnabled);
if (newSettingsMap.get("scrollbarFadingEnabled") != null && !customSettings.scrollbarFadingEnabled.equals(newSettings.scrollbarFadingEnabled))
setScrollbarFadingEnabled(newSettings.scrollbarFadingEnabled);
if (newOptionsMap.get("scrollBarFadeDuration") != null && (options.scrollBarFadeDuration == null ||
!options.scrollBarFadeDuration.equals(newOptions.scrollBarFadeDuration)))
setScrollBarFadeDuration(newOptions.scrollBarFadeDuration);
if (newSettingsMap.get("scrollBarFadeDuration") != null && (customSettings.scrollBarFadeDuration == null ||
!customSettings.scrollBarFadeDuration.equals(newSettings.scrollBarFadeDuration)))
setScrollBarFadeDuration(newSettings.scrollBarFadeDuration);
if (newOptionsMap.get("verticalScrollbarPosition") != null && !options.verticalScrollbarPosition.equals(newOptions.verticalScrollbarPosition))
setVerticalScrollbarPosition(newOptions.verticalScrollbarPosition);
if (newSettingsMap.get("verticalScrollbarPosition") != null && !customSettings.verticalScrollbarPosition.equals(newSettings.verticalScrollbarPosition))
setVerticalScrollbarPosition(newSettings.verticalScrollbarPosition);
if (newOptionsMap.get("disableVerticalScroll") != null && options.disableVerticalScroll != newOptions.disableVerticalScroll)
setVerticalScrollBarEnabled(!newOptions.disableVerticalScroll && newOptions.verticalScrollBarEnabled);
if (newSettingsMap.get("disableVerticalScroll") != null && customSettings.disableVerticalScroll != newSettings.disableVerticalScroll)
setVerticalScrollBarEnabled(!newSettings.disableVerticalScroll && newSettings.verticalScrollBarEnabled);
if (newOptionsMap.get("disableHorizontalScroll") != null && options.disableHorizontalScroll != newOptions.disableHorizontalScroll)
setHorizontalScrollBarEnabled(!newOptions.disableHorizontalScroll && newOptions.horizontalScrollBarEnabled);
if (newSettingsMap.get("disableHorizontalScroll") != null && customSettings.disableHorizontalScroll != newSettings.disableHorizontalScroll)
setHorizontalScrollBarEnabled(!newSettings.disableHorizontalScroll && newSettings.horizontalScrollBarEnabled);
if (newOptionsMap.get("overScrollMode") != null && !options.overScrollMode.equals(newOptions.overScrollMode))
setOverScrollMode(newOptions.overScrollMode);
if (newSettingsMap.get("overScrollMode") != null && !customSettings.overScrollMode.equals(newSettings.overScrollMode))
setOverScrollMode(newSettings.overScrollMode);
if (newOptionsMap.get("networkAvailable") != null && options.networkAvailable != newOptions.networkAvailable)
setNetworkAvailable(newOptions.networkAvailable);
if (newSettingsMap.get("networkAvailable") != null && customSettings.networkAvailable != newSettings.networkAvailable)
setNetworkAvailable(newSettings.networkAvailable);
if (newOptionsMap.get("rendererPriorityPolicy") != null &&
(options.rendererPriorityPolicy.get("rendererRequestedPriority") != newOptions.rendererPriorityPolicy.get("rendererRequestedPriority") ||
options.rendererPriorityPolicy.get("waivedWhenNotVisible") != newOptions.rendererPriorityPolicy.get("waivedWhenNotVisible")) &&
if (newSettingsMap.get("rendererPriorityPolicy") != null &&
(customSettings.rendererPriorityPolicy.get("rendererRequestedPriority") != newSettings.rendererPriorityPolicy.get("rendererRequestedPriority") ||
customSettings.rendererPriorityPolicy.get("waivedWhenNotVisible") != newSettings.rendererPriorityPolicy.get("waivedWhenNotVisible")) &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setRendererPriorityPolicy(
(int) newOptions.rendererPriorityPolicy.get("rendererRequestedPriority"),
(boolean) newOptions.rendererPriorityPolicy.get("waivedWhenNotVisible"));
(int) newSettings.rendererPriorityPolicy.get("rendererRequestedPriority"),
(boolean) newSettings.rendererPriorityPolicy.get("waivedWhenNotVisible"));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (newOptionsMap.get("verticalScrollbarThumbColor") != null && !Util.objEquals(options.verticalScrollbarThumbColor, newOptions.verticalScrollbarThumbColor))
setVerticalScrollbarThumbDrawable(new ColorDrawable(Color.parseColor(newOptions.verticalScrollbarThumbColor)));
if (newSettingsMap.get("verticalScrollbarThumbColor") != null && !Util.objEquals(customSettings.verticalScrollbarThumbColor, newSettings.verticalScrollbarThumbColor))
setVerticalScrollbarThumbDrawable(new ColorDrawable(Color.parseColor(newSettings.verticalScrollbarThumbColor)));
if (newOptionsMap.get("verticalScrollbarTrackColor") != null && !Util.objEquals(options.verticalScrollbarTrackColor, newOptions.verticalScrollbarTrackColor))
setVerticalScrollbarTrackDrawable(new ColorDrawable(Color.parseColor(newOptions.verticalScrollbarTrackColor)));
if (newSettingsMap.get("verticalScrollbarTrackColor") != null && !Util.objEquals(customSettings.verticalScrollbarTrackColor, newSettings.verticalScrollbarTrackColor))
setVerticalScrollbarTrackDrawable(new ColorDrawable(Color.parseColor(newSettings.verticalScrollbarTrackColor)));
if (newOptionsMap.get("horizontalScrollbarThumbColor") != null && !Util.objEquals(options.horizontalScrollbarThumbColor, newOptions.horizontalScrollbarThumbColor))
setHorizontalScrollbarThumbDrawable(new ColorDrawable(Color.parseColor(newOptions.horizontalScrollbarThumbColor)));
if (newSettingsMap.get("horizontalScrollbarThumbColor") != null && !Util.objEquals(customSettings.horizontalScrollbarThumbColor, newSettings.horizontalScrollbarThumbColor))
setHorizontalScrollbarThumbDrawable(new ColorDrawable(Color.parseColor(newSettings.horizontalScrollbarThumbColor)));
if (newOptionsMap.get("horizontalScrollbarTrackColor") != null && !Util.objEquals(options.horizontalScrollbarTrackColor, newOptions.horizontalScrollbarTrackColor))
setHorizontalScrollbarTrackDrawable(new ColorDrawable(Color.parseColor(newOptions.horizontalScrollbarTrackColor)));
if (newSettingsMap.get("horizontalScrollbarTrackColor") != null && !Util.objEquals(customSettings.horizontalScrollbarTrackColor, newSettings.horizontalScrollbarTrackColor))
setHorizontalScrollbarTrackDrawable(new ColorDrawable(Color.parseColor(newSettings.horizontalScrollbarTrackColor)));
}
options = newOptions;
customSettings = newSettings;
}
public Map<String, Object> getOptions() {
return (options != null) ? options.getRealOptions(this) : null;
public Map<String, Object> getCustomSettings() {
return (customSettings != null) ? customSettings.getRealSettings(this) : null;
}
public void enablePluginScriptAtRuntime(final String flagVariable,
@ -1278,7 +1277,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
setOverScrollMode(OVER_SCROLL_NEVER);
pullToRefreshLayout.setEnabled(pullToRefreshLayout.options.enabled);
// reset over scroll mode
setOverScrollMode(options.overScrollMode);
setOverScrollMode(customSettings.overScrollMode);
}
if (overScrolledHorizontally || overScrolledVertically) {
@ -1299,7 +1298,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection connection = super.onCreateInputConnection(outAttrs);
if (connection == null && !options.useHybridComposition && containerView != null) {
if (connection == null && !customSettings.useHybridComposition && containerView != null) {
// workaround to hide the Keyboard when the user click outside
// on something not focusable such as input or a textarea.
containerView
@ -1323,7 +1322,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
@Override
public ActionMode startActionMode(ActionMode.Callback callback) {
if (options.useHybridComposition && !options.disableContextMenu && (contextMenu == null || contextMenu.keySet().size() == 0)) {
if (customSettings.useHybridComposition && !customSettings.disableContextMenu && (contextMenu == null || contextMenu.keySet().size() == 0)) {
return super.startActionMode(callback);
}
return rebuildActionMode(super.startActionMode(callback), callback);
@ -1332,7 +1331,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public ActionMode startActionMode(ActionMode.Callback callback, int type) {
if (options.useHybridComposition && !options.disableContextMenu && (contextMenu == null || contextMenu.keySet().size() == 0)) {
if (customSettings.useHybridComposition && !customSettings.disableContextMenu && (contextMenu == null || contextMenu.keySet().size() == 0)) {
return super.startActionMode(callback, type);
}
return rebuildActionMode(super.startActionMode(callback, type), callback);
@ -1343,7 +1342,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
final ActionMode.Callback callback
) {
// fix Android 10 clipboard not working properly https://github.com/pichillilorenzo/flutter_inappwebview/issues/678
if (!options.useHybridComposition && containerView != null) {
if (!customSettings.useHybridComposition && containerView != null) {
onWindowFocusChanged(containerView.isFocused());
}
@ -1357,7 +1356,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
}
Menu actionMenu = actionMode.getMenu();
if (options.disableContextMenu) {
if (customSettings.disableContextMenu) {
actionMenu.clear();
return actionMode;
}

View File

@ -172,7 +172,7 @@ public class InAppWebViewChromeClient extends WebChromeClient implements PluginR
Map<String, Object> obj = new HashMap<>();
obj.put("url", url);
obj.put("message", message);
obj.put("iosIsMainFrame", null);
obj.put("isMainFrame", null);
channel.invokeMethod("onJsAlert", obj, new MethodChannel.Result() {
@Override
@ -257,7 +257,7 @@ public class InAppWebViewChromeClient extends WebChromeClient implements PluginR
Map<String, Object> obj = new HashMap<>();
obj.put("url", url);
obj.put("message", message);
obj.put("iosIsMainFrame", null);
obj.put("isMainFrame", null);
channel.invokeMethod("onJsConfirm", obj, new MethodChannel.Result() {
@Override
@ -356,7 +356,7 @@ public class InAppWebViewChromeClient extends WebChromeClient implements PluginR
obj.put("url", url);
obj.put("message", message);
obj.put("defaultValue", defaultValue);
obj.put("iosIsMainFrame", null);
obj.put("isMainFrame", null);
channel.invokeMethod("onJsPrompt", obj, new MethodChannel.Result() {
@Override

View File

@ -68,7 +68,7 @@ public class InAppWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
InAppWebView webView = (InAppWebView) view;
if (webView.options.useShouldOverrideUrlLoading) {
if (webView.customSettings.useShouldOverrideUrlLoading) {
boolean isRedirect = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
isRedirect = request.isRedirect();
@ -100,7 +100,7 @@ public class InAppWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
InAppWebView inAppWebView = (InAppWebView) webView;
if (inAppWebView.options.useShouldOverrideUrlLoading) {
if (inAppWebView.customSettings.useShouldOverrideUrlLoading) {
onShouldOverrideUrlLoading(inAppWebView, url, "GET", null,true, false, false);
return true;
}
@ -254,7 +254,7 @@ public class InAppWebViewClient extends WebViewClient {
Map<String, Object> obj = new HashMap<>();
// url argument sometimes doesn't contain the new changed URL, so we get it again from the webview.
obj.put("url", url);
obj.put("androidIsReload", isReload);
obj.put("isReload", isReload);
channel.invokeMethod("onUpdateVisitedHistory", obj);
}
@ -291,7 +291,7 @@ public class InAppWebViewClient extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
final InAppWebView webView = (InAppWebView) view;
if (webView.options.disableDefaultErrorPage) {
if (webView.customSettings.disableDefaultErrorPage) {
webView.stopLoading();
webView.loadUrl("about:blank");
}
@ -602,7 +602,7 @@ public class InAppWebViewClient extends WebViewClient {
final InAppWebView webView = (InAppWebView) view;
if (webView.options.useShouldInterceptRequest) {
if (webView.customSettings.useShouldInterceptRequest) {
WebResourceResponse onShouldInterceptResponse = onShouldInterceptRequest(url);
return onShouldInterceptResponse;
}
@ -624,7 +624,7 @@ public class InAppWebViewClient extends WebViewClient {
String scheme = uri.getScheme();
if (webView.options.resourceCustomSchemes != null && webView.options.resourceCustomSchemes.contains(scheme)) {
if (webView.customSettings.resourceCustomSchemes != null && webView.customSettings.resourceCustomSchemes.contains(scheme)) {
final Map<String, Object> obj = new HashMap<>();
obj.put("url", url);
@ -672,7 +672,7 @@ public class InAppWebViewClient extends WebViewClient {
String url = request.getUrl().toString();
if (webView.options.useShouldInterceptRequest) {
if (webView.customSettings.useShouldInterceptRequest) {
WebResourceResponse onShouldInterceptResponse = onShouldInterceptRequest(request);
return onShouldInterceptResponse;
}
@ -792,7 +792,7 @@ public class InAppWebViewClient extends WebViewClient {
public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
final InAppWebView webView = (InAppWebView) view;
if (webView.options.useOnRenderProcessGone) {
if (webView.customSettings.useOnRenderProcessGone) {
Boolean didCrash = detail.didCrash();
Integer rendererPriorityAtExit = detail.rendererPriorityAtExit();

View File

@ -6,7 +6,7 @@ import android.webkit.WebSettings;
import androidx.annotation.Nullable;
import com.pichillilorenzo.flutter_inappwebview.Options;
import com.pichillilorenzo.flutter_inappwebview.IWebViewSettings;
import com.pichillilorenzo.flutter_inappwebview.types.InAppWebViewInterface;
import com.pichillilorenzo.flutter_inappwebview.types.PreferredContentModeOptionType;
@ -18,9 +18,9 @@ import java.util.Map;
import static android.webkit.WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
import static android.webkit.WebSettings.LayoutAlgorithm.NORMAL;
public class InAppWebViewOptions implements Options<InAppWebViewInterface> {
public class InAppWebViewSettings implements IWebViewSettings<InAppWebViewInterface> {
public static final String LOG_TAG = "InAppWebViewOptions";
public static final String LOG_TAG = "InAppWebViewSettings";
public Boolean useShouldOverrideUrlLoading = false;
public Boolean useOnLoadResource = false;
@ -110,8 +110,8 @@ public class InAppWebViewOptions implements Options<InAppWebViewInterface> {
public String horizontalScrollbarTrackColor;
@Override
public InAppWebViewOptions parse(Map<String, Object> options) {
for (Map.Entry<String, Object> pair : options.entrySet()) {
public InAppWebViewSettings parse(Map<String, Object> settings) {
for (Map.Entry<String, Object> pair : settings.entrySet()) {
String key = pair.getKey();
Object value = pair.getValue();
if (value == null) {
@ -370,162 +370,162 @@ public class InAppWebViewOptions implements Options<InAppWebViewInterface> {
@Override
public Map<String, Object> toMap() {
Map<String, Object> options = new HashMap<>();
options.put("useShouldOverrideUrlLoading", useShouldOverrideUrlLoading);
options.put("useOnLoadResource", useOnLoadResource);
options.put("useOnDownloadStart", useOnDownloadStart);
options.put("clearCache", clearCache);
options.put("userAgent", userAgent);
options.put("applicationNameForUserAgent", applicationNameForUserAgent);
options.put("javaScriptEnabled", javaScriptEnabled);
options.put("javaScriptCanOpenWindowsAutomatically", javaScriptCanOpenWindowsAutomatically);
options.put("mediaPlaybackRequiresUserGesture", mediaPlaybackRequiresUserGesture);
options.put("minimumFontSize", minimumFontSize);
options.put("verticalScrollBarEnabled", verticalScrollBarEnabled);
options.put("horizontalScrollBarEnabled", horizontalScrollBarEnabled);
options.put("resourceCustomSchemes", resourceCustomSchemes);
options.put("contentBlockers", contentBlockers);
options.put("preferredContentMode", preferredContentMode);
options.put("useShouldInterceptAjaxRequest", useShouldInterceptAjaxRequest);
options.put("useShouldInterceptFetchRequest", useShouldInterceptFetchRequest);
options.put("incognito", incognito);
options.put("cacheEnabled", cacheEnabled);
options.put("transparentBackground", transparentBackground);
options.put("disableVerticalScroll", disableVerticalScroll);
options.put("disableHorizontalScroll", disableHorizontalScroll);
options.put("disableContextMenu", disableContextMenu);
options.put("textZoom", textZoom);
options.put("clearSessionCache", clearSessionCache);
options.put("builtInZoomControls", builtInZoomControls);
options.put("displayZoomControls", displayZoomControls);
options.put("supportZoom", supportZoom);
options.put("databaseEnabled", databaseEnabled);
options.put("domStorageEnabled", domStorageEnabled);
options.put("useWideViewPort", useWideViewPort);
options.put("safeBrowsingEnabled", safeBrowsingEnabled);
options.put("mixedContentMode", mixedContentMode);
options.put("allowContentAccess", allowContentAccess);
options.put("allowFileAccess", allowFileAccess);
options.put("allowFileAccessFromFileURLs", allowFileAccessFromFileURLs);
options.put("allowUniversalAccessFromFileURLs", allowUniversalAccessFromFileURLs);
options.put("appCachePath", appCachePath);
options.put("blockNetworkImage", blockNetworkImage);
options.put("blockNetworkLoads", blockNetworkLoads);
options.put("cacheMode", cacheMode);
options.put("cursiveFontFamily", cursiveFontFamily);
options.put("defaultFixedFontSize", defaultFixedFontSize);
options.put("defaultFontSize", defaultFontSize);
options.put("defaultTextEncodingName", defaultTextEncodingName);
options.put("disabledActionModeMenuItems", disabledActionModeMenuItems);
options.put("fantasyFontFamily", fantasyFontFamily);
options.put("fixedFontFamily", fixedFontFamily);
options.put("forceDark", forceDark);
options.put("geolocationEnabled", geolocationEnabled);
options.put("layoutAlgorithm", getLayoutAlgorithm());
options.put("loadWithOverviewMode", loadWithOverviewMode);
options.put("loadsImagesAutomatically", loadsImagesAutomatically);
options.put("minimumLogicalFontSize", minimumLogicalFontSize);
options.put("initialScale", initialScale);
options.put("needInitialFocus", needInitialFocus);
options.put("offscreenPreRaster", offscreenPreRaster);
options.put("sansSerifFontFamily", sansSerifFontFamily);
options.put("serifFontFamily", serifFontFamily);
options.put("standardFontFamily", standardFontFamily);
options.put("saveFormData", saveFormData);
options.put("thirdPartyCookiesEnabled", thirdPartyCookiesEnabled);
options.put("hardwareAcceleration", hardwareAcceleration);
options.put("supportMultipleWindows", supportMultipleWindows);
options.put("regexToCancelSubFramesLoading", regexToCancelSubFramesLoading);
options.put("overScrollMode", overScrollMode);
options.put("networkAvailable", networkAvailable);
options.put("scrollBarStyle", scrollBarStyle);
options.put("verticalScrollbarPosition", verticalScrollbarPosition);
options.put("scrollBarDefaultDelayBeforeFade", scrollBarDefaultDelayBeforeFade);
options.put("scrollbarFadingEnabled", scrollbarFadingEnabled);
options.put("scrollBarFadeDuration", scrollBarFadeDuration);
options.put("rendererPriorityPolicy", rendererPriorityPolicy);
options.put("useShouldInterceptRequest", useShouldInterceptRequest);
options.put("useOnRenderProcessGone", useOnRenderProcessGone);
options.put("disableDefaultErrorPage", disableDefaultErrorPage);
options.put("useHybridComposition", useHybridComposition);
options.put("verticalScrollbarThumbColor", verticalScrollbarThumbColor);
options.put("verticalScrollbarTrackColor", verticalScrollbarTrackColor);
options.put("horizontalScrollbarThumbColor", horizontalScrollbarThumbColor);
options.put("horizontalScrollbarTrackColor", horizontalScrollbarTrackColor);
return options;
Map<String, Object> settings = new HashMap<>();
settings.put("useShouldOverrideUrlLoading", useShouldOverrideUrlLoading);
settings.put("useOnLoadResource", useOnLoadResource);
settings.put("useOnDownloadStart", useOnDownloadStart);
settings.put("clearCache", clearCache);
settings.put("userAgent", userAgent);
settings.put("applicationNameForUserAgent", applicationNameForUserAgent);
settings.put("javaScriptEnabled", javaScriptEnabled);
settings.put("javaScriptCanOpenWindowsAutomatically", javaScriptCanOpenWindowsAutomatically);
settings.put("mediaPlaybackRequiresUserGesture", mediaPlaybackRequiresUserGesture);
settings.put("minimumFontSize", minimumFontSize);
settings.put("verticalScrollBarEnabled", verticalScrollBarEnabled);
settings.put("horizontalScrollBarEnabled", horizontalScrollBarEnabled);
settings.put("resourceCustomSchemes", resourceCustomSchemes);
settings.put("contentBlockers", contentBlockers);
settings.put("preferredContentMode", preferredContentMode);
settings.put("useShouldInterceptAjaxRequest", useShouldInterceptAjaxRequest);
settings.put("useShouldInterceptFetchRequest", useShouldInterceptFetchRequest);
settings.put("incognito", incognito);
settings.put("cacheEnabled", cacheEnabled);
settings.put("transparentBackground", transparentBackground);
settings.put("disableVerticalScroll", disableVerticalScroll);
settings.put("disableHorizontalScroll", disableHorizontalScroll);
settings.put("disableContextMenu", disableContextMenu);
settings.put("textZoom", textZoom);
settings.put("clearSessionCache", clearSessionCache);
settings.put("builtInZoomControls", builtInZoomControls);
settings.put("displayZoomControls", displayZoomControls);
settings.put("supportZoom", supportZoom);
settings.put("databaseEnabled", databaseEnabled);
settings.put("domStorageEnabled", domStorageEnabled);
settings.put("useWideViewPort", useWideViewPort);
settings.put("safeBrowsingEnabled", safeBrowsingEnabled);
settings.put("mixedContentMode", mixedContentMode);
settings.put("allowContentAccess", allowContentAccess);
settings.put("allowFileAccess", allowFileAccess);
settings.put("allowFileAccessFromFileURLs", allowFileAccessFromFileURLs);
settings.put("allowUniversalAccessFromFileURLs", allowUniversalAccessFromFileURLs);
settings.put("appCachePath", appCachePath);
settings.put("blockNetworkImage", blockNetworkImage);
settings.put("blockNetworkLoads", blockNetworkLoads);
settings.put("cacheMode", cacheMode);
settings.put("cursiveFontFamily", cursiveFontFamily);
settings.put("defaultFixedFontSize", defaultFixedFontSize);
settings.put("defaultFontSize", defaultFontSize);
settings.put("defaultTextEncodingName", defaultTextEncodingName);
settings.put("disabledActionModeMenuItems", disabledActionModeMenuItems);
settings.put("fantasyFontFamily", fantasyFontFamily);
settings.put("fixedFontFamily", fixedFontFamily);
settings.put("forceDark", forceDark);
settings.put("geolocationEnabled", geolocationEnabled);
settings.put("layoutAlgorithm", getLayoutAlgorithm());
settings.put("loadWithOverviewMode", loadWithOverviewMode);
settings.put("loadsImagesAutomatically", loadsImagesAutomatically);
settings.put("minimumLogicalFontSize", minimumLogicalFontSize);
settings.put("initialScale", initialScale);
settings.put("needInitialFocus", needInitialFocus);
settings.put("offscreenPreRaster", offscreenPreRaster);
settings.put("sansSerifFontFamily", sansSerifFontFamily);
settings.put("serifFontFamily", serifFontFamily);
settings.put("standardFontFamily", standardFontFamily);
settings.put("saveFormData", saveFormData);
settings.put("thirdPartyCookiesEnabled", thirdPartyCookiesEnabled);
settings.put("hardwareAcceleration", hardwareAcceleration);
settings.put("supportMultipleWindows", supportMultipleWindows);
settings.put("regexToCancelSubFramesLoading", regexToCancelSubFramesLoading);
settings.put("overScrollMode", overScrollMode);
settings.put("networkAvailable", networkAvailable);
settings.put("scrollBarStyle", scrollBarStyle);
settings.put("verticalScrollbarPosition", verticalScrollbarPosition);
settings.put("scrollBarDefaultDelayBeforeFade", scrollBarDefaultDelayBeforeFade);
settings.put("scrollbarFadingEnabled", scrollbarFadingEnabled);
settings.put("scrollBarFadeDuration", scrollBarFadeDuration);
settings.put("rendererPriorityPolicy", rendererPriorityPolicy);
settings.put("useShouldInterceptRequest", useShouldInterceptRequest);
settings.put("useOnRenderProcessGone", useOnRenderProcessGone);
settings.put("disableDefaultErrorPage", disableDefaultErrorPage);
settings.put("useHybridComposition", useHybridComposition);
settings.put("verticalScrollbarThumbColor", verticalScrollbarThumbColor);
settings.put("verticalScrollbarTrackColor", verticalScrollbarTrackColor);
settings.put("horizontalScrollbarThumbColor", horizontalScrollbarThumbColor);
settings.put("horizontalScrollbarTrackColor", horizontalScrollbarTrackColor);
return settings;
}
@Override
public Map<String, Object> getRealOptions(InAppWebViewInterface inAppWebView) {
Map<String, Object> realOptions = toMap();
public Map<String, Object> getRealSettings(InAppWebViewInterface inAppWebView) {
Map<String, Object> realSettings = toMap();
if (inAppWebView instanceof InAppWebView) {
InAppWebView webView = (InAppWebView) inAppWebView;
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());
realSettings.put("userAgent", settings.getUserAgentString());
realSettings.put("javaScriptEnabled", settings.getJavaScriptEnabled());
realSettings.put("javaScriptCanOpenWindowsAutomatically", settings.getJavaScriptCanOpenWindowsAutomatically());
realSettings.put("mediaPlaybackRequiresUserGesture", settings.getMediaPlaybackRequiresUserGesture());
realSettings.put("minimumFontSize", settings.getMinimumFontSize());
realSettings.put("verticalScrollBarEnabled", webView.isVerticalScrollBarEnabled());
realSettings.put("horizontalScrollBarEnabled", webView.isHorizontalScrollBarEnabled());
realSettings.put("textZoom", settings.getTextZoom());
realSettings.put("builtInZoomControls", settings.getBuiltInZoomControls());
realSettings.put("supportZoom", settings.supportZoom());
realSettings.put("displayZoomControls", settings.getDisplayZoomControls());
realSettings.put("databaseEnabled", settings.getDatabaseEnabled());
realSettings.put("domStorageEnabled", settings.getDomStorageEnabled());
realSettings.put("useWideViewPort", settings.getUseWideViewPort());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
realOptions.put("safeBrowsingEnabled", settings.getSafeBrowsingEnabled());
realSettings.put("safeBrowsingEnabled", settings.getSafeBrowsingEnabled());
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
realOptions.put("mixedContentMode", settings.getMixedContentMode());
realSettings.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());
realSettings.put("allowContentAccess", settings.getAllowContentAccess());
realSettings.put("allowFileAccess", settings.getAllowFileAccess());
realSettings.put("allowFileAccessFromFileURLs", settings.getAllowFileAccessFromFileURLs());
realSettings.put("allowUniversalAccessFromFileURLs", settings.getAllowUniversalAccessFromFileURLs());
realSettings.put("blockNetworkImage", settings.getBlockNetworkImage());
realSettings.put("blockNetworkLoads", settings.getBlockNetworkLoads());
realSettings.put("cacheMode", settings.getCacheMode());
realSettings.put("cursiveFontFamily", settings.getCursiveFontFamily());
realSettings.put("defaultFixedFontSize", settings.getDefaultFixedFontSize());
realSettings.put("defaultFontSize", settings.getDefaultFontSize());
realSettings.put("defaultTextEncodingName", settings.getDefaultTextEncodingName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
realOptions.put("disabledActionModeMenuItems", settings.getDisabledActionModeMenuItems());
realSettings.put("disabledActionModeMenuItems", settings.getDisabledActionModeMenuItems());
}
realOptions.put("fantasyFontFamily", settings.getFantasyFontFamily());
realOptions.put("fixedFontFamily", settings.getFixedFontFamily());
realSettings.put("fantasyFontFamily", settings.getFantasyFontFamily());
realSettings.put("fixedFontFamily", settings.getFixedFontFamily());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
realOptions.put("forceDark", settings.getForceDark());
realSettings.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());
realSettings.put("layoutAlgorithm", settings.getLayoutAlgorithm().name());
realSettings.put("loadWithOverviewMode", settings.getLoadWithOverviewMode());
realSettings.put("loadsImagesAutomatically", settings.getLoadsImagesAutomatically());
realSettings.put("minimumLogicalFontSize", settings.getMinimumLogicalFontSize());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
realOptions.put("offscreenPreRaster", settings.getOffscreenPreRaster());
realSettings.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());
realSettings.put("sansSerifFontFamily", settings.getSansSerifFontFamily());
realSettings.put("serifFontFamily", settings.getSerifFontFamily());
realSettings.put("standardFontFamily", settings.getStandardFontFamily());
realSettings.put("saveFormData", settings.getSaveFormData());
realSettings.put("supportMultipleWindows", settings.supportMultipleWindows());
realSettings.put("overScrollMode", webView.getOverScrollMode());
realSettings.put("scrollBarStyle", webView.getScrollBarStyle());
realSettings.put("verticalScrollbarPosition", webView.getVerticalScrollbarPosition());
realSettings.put("scrollBarDefaultDelayBeforeFade", webView.getScrollBarDefaultDelayBeforeFade());
realSettings.put("scrollbarFadingEnabled", webView.isScrollbarFadingEnabled());
realSettings.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);
realSettings.put("rendererPriorityPolicy", rendererPriorityPolicy);
}
}
return realOptions;
return realSettings;
}
private void setLayoutAlgorithm(String value) {

View File

@ -3,17 +3,12 @@ package com.pichillilorenzo.flutter_inappwebview.pull_to_refresh;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.pichillilorenzo.flutter_inappwebview.R;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebView;
import java.util.HashMap;

View File

@ -31,8 +31,8 @@ public class ClientCertChallenge extends URLAuthenticationChallenge {
}
Map<String, Object> challengeMap = super.toMap();
challengeMap.put("androidPrincipals", principalList);
challengeMap.put("androidKeyTypes", keyTypes != null ? Arrays.asList(keyTypes) : null);
challengeMap.put("principals", principalList);
challengeMap.put("keyTypes", keyTypes != null ? Arrays.asList(keyTypes) : null);
return challengeMap;
}

View File

@ -15,7 +15,8 @@ public class CreateWindowAction extends NavigationAction {
public Map<String, Object> toMap() {
Map<String, Object> createWindowActionMap = super.toMap();
createWindowActionMap.put("windowId", windowId);
createWindowActionMap.put("androidIsDialog", isDialog);
createWindowActionMap.put("isDialog", isDialog);
createWindowActionMap.put("windowFeatures", null);
return createWindowActionMap;
}

View File

@ -19,6 +19,8 @@ public class HttpAuthenticationChallenge extends URLAuthenticationChallenge {
Map<String, Object> challengeMap = super.toMap();
challengeMap.put("previousFailureCount", previousFailureCount);
challengeMap.put("proposedCredential", (proposedCredential != null) ? proposedCredential.toMap() : null);
challengeMap.put("failureResponse", null);
challengeMap.put("error", null);
return challengeMap;
}

View File

@ -10,7 +10,7 @@ import android.webkit.WebView;
import com.pichillilorenzo.flutter_inappwebview.InAppWebViewFlutterPlugin;
import com.pichillilorenzo.flutter_inappwebview.in_app_browser.InAppBrowserDelegate;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebViewOptions;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.InAppWebViewSettings;
import java.io.IOException;
import java.util.HashMap;
@ -42,8 +42,8 @@ public interface InAppWebViewInterface {
void stopLoading();
boolean isLoading();
void takeScreenshot(Map<String, Object> screenshotConfiguration, MethodChannel.Result result);
void setOptions(InAppWebViewOptions newOptions, HashMap<String, Object> newOptionsMap);
Map<String, Object> getOptions();
void setSettings(InAppWebViewSettings newSettings, HashMap<String, Object> newSettingsMap);
Map<String, Object> getCustomSettings();
HashMap<String, Object> getCopyBackForwardList();
void clearAllCache();
void clearSslPreferences();

View File

@ -20,8 +20,11 @@ public class NavigationAction {
Map<String, Object> navigationActionMap = new HashMap<>();
navigationActionMap.put("request", request.toMap());
navigationActionMap.put("isForMainFrame", isForMainFrame);
navigationActionMap.put("androidHasGesture", hasGesture);
navigationActionMap.put("androidIsRedirect", isRedirect);
navigationActionMap.put("hasGesture", hasGesture);
navigationActionMap.put("isRedirect", isRedirect);
navigationActionMap.put("navigationType", null);
navigationActionMap.put("sourceFrame", null);
navigationActionMap.put("targetFrame", null);
return navigationActionMap;
}

View File

@ -48,7 +48,7 @@ public class SslErrorExt extends SslError {
}
Map<String, Object> urlProtectionSpaceMap = new HashMap<>();
urlProtectionSpaceMap.put("androidError", primaryError);
urlProtectionSpaceMap.put("code", primaryError >= 0 ? primaryError : null);
urlProtectionSpaceMap.put("message", message);
return urlProtectionSpaceMap;
}

View File

@ -32,6 +32,8 @@ public class URLCredential {
Map<String, Object> urlCredentialMap = new HashMap<>();
urlCredentialMap.put("username", username);
urlCredentialMap.put("password", password);
urlCredentialMap.put("certificates", null);
urlCredentialMap.put("persistence", null);
return urlCredentialMap;
}

View File

@ -46,6 +46,11 @@ public class URLProtectionSpace {
urlProtectionSpaceMap.put("port", port);
urlProtectionSpaceMap.put("sslCertificate", SslCertificateExt.toMap(sslCertificate));
urlProtectionSpaceMap.put("sslError", SslErrorExt.toMap(sslError));
urlProtectionSpaceMap.put("authenticationMethod", null);
urlProtectionSpaceMap.put("distinguishedNames", null);
urlProtectionSpaceMap.put("receivesCredentialSecurely", null);
urlProtectionSpaceMap.put("isProxy", null);
urlProtectionSpaceMap.put("proxyType", null);
return urlProtectionSpaceMap;
}

View File

@ -41,7 +41,17 @@ public class URLRequest {
Map<String, Object> urlRequestMap = new HashMap<>();
urlRequestMap.put("url", url);
urlRequestMap.put("method", method);
urlRequestMap.put("headers", headers);
urlRequestMap.put("body", body);
urlRequestMap.put("allowsCellularAccess", null);
urlRequestMap.put("allowsConstrainedNetworkAccess", null);
urlRequestMap.put("allowsExpensiveNetworkAccess", null);
urlRequestMap.put("cachePolicy", null);
urlRequestMap.put("httpShouldHandleCookies", null);
urlRequestMap.put("httpShouldUsePipelining", null);
urlRequestMap.put("networkServiceType", null);
urlRequestMap.put("timeoutInterval", null);
urlRequestMap.put("mainDocumentURL", null);
return urlRequestMap;
}

View File

@ -21,9 +21,7 @@ class _HeadlessInAppWebViewExampleScreenState
headlessWebView = new HeadlessInAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse("https://flutter.dev")),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(),
),
initialSettings: InAppWebViewSettings(),
onWebViewCreated: (controller) {
print('HeadlessInAppWebView created!');
},

View File

@ -123,12 +123,13 @@ class _InAppBrowserExampleScreenState extends State<InAppBrowserExampleScreen> {
await widget.browser.openUrlRequest(
urlRequest:
URLRequest(url: Uri.parse("https://flutter.dev")),
options: InAppBrowserClassOptions(
inAppWebViewGroupOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
useShouldOverrideUrlLoading: true,
useOnLoadResource: true,
))));
settings: InAppBrowserClassSettings(
webViewSettings: InAppWebViewSettings(
useShouldOverrideUrlLoading: true,
useOnLoadResource: true,
),
),
);
},
child: Text("Open In-App Browser")),
Container(height: 40),

View File

@ -21,17 +21,12 @@ class _InAppWebViewExampleScreenState extends State<InAppWebViewExampleScreen> {
final GlobalKey webViewKey = GlobalKey();
InAppWebViewController? webViewController;
InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
useShouldOverrideUrlLoading: true,
mediaPlaybackRequiresUserGesture: false
),
android: AndroidInAppWebViewOptions(
useHybridComposition: true,
),
ios: IOSInAppWebViewOptions(
allowsInlineMediaPlayback: true,
));
InAppWebViewSettings settings = InAppWebViewSettings(
useShouldOverrideUrlLoading: true,
mediaPlaybackRequiresUserGesture: false,
useHybridComposition: true,
allowsInlineMediaPlayback: true,
);
late PullToRefreshController pullToRefreshController;
late ContextMenu contextMenu;
@ -126,7 +121,7 @@ class _InAppWebViewExampleScreenState extends State<InAppWebViewExampleScreen> {
URLRequest(url: Uri.parse("https://github.com/flutter")),
// initialFile: "assets/index.html",
initialUserScripts: UnmodifiableListView<UserScript>([]),
initialOptions: options,
initialSettings: settings,
pullToRefreshController: pullToRefreshController,
onWebViewCreated: (controller) {
webViewController = controller;

View File

@ -7,7 +7,7 @@
import Foundation
class ContextMenuOptions: Options<NSObject> {
class ContextMenuOptions: IWebViewSettings<NSObject> {
var hideDefaultSystemContextMenuItems = false;

View File

@ -26,8 +26,8 @@ class HttpAuthenticationChallenge: NSObject {
return [
"protectionSpace": protectionSpace.toMap(),
"previousFailureCount": previousFailureCount,
"iosFailureResponse": failureResponse?.toMap(),
"iosError": error?.localizedDescription,
"failureResponse": failureResponse?.toMap(),
"error": error?.localizedDescription,
"proposedCredential": proposedCredential?.toMap()
]
}

View File

@ -14,8 +14,8 @@ public class IWebViewSettings<T>: NSObject {
super.init()
}
func parse(options: [String: Any?]) -> IWebViewSettings {
for (key, value) in options {
func parse(settings: [String: Any?]) -> IWebViewSettings {
for (key, value) in settings {
if !(value is NSNull), value != nil, self.responds(to: Selector(key)) {
self.setValue(value, forKey: key)
}
@ -24,7 +24,7 @@ public class IWebViewSettings<T>: NSObject {
}
func toMap() -> [String: Any?] {
var options: [String: Any?] = [:]
var settings: [String: Any?] = [:]
var counts = UInt32();
let properties = class_copyPropertyList(object_getClass(self), &counts);
for i in 0..<counts {
@ -33,14 +33,14 @@ public class IWebViewSettings<T>: NSObject {
let cName = property_getName(property!);
let name = String(cString: cName)
options[name] = self.value(forKey: name)
settings[name] = self.value(forKey: name)
}
free(properties)
return options
return settings
}
func getRealOptions(obj: T?) -> [String: Any?] {
let realOptions: [String: Any?] = toMap()
return realOptions
func getRealSettings(obj: T?) -> [String: Any?] {
let realSettings: [String: Any?] = toMap()
return realSettings
}
}

View File

@ -50,20 +50,20 @@ public class InAppBrowserManager: NSObject, FlutterPlugin {
}
}
public func prepareInAppBrowserWebViewController(options: [String: Any?]) -> InAppBrowserWebViewController {
public func prepareInAppBrowserWebViewController(settings: [String: Any?]) -> InAppBrowserWebViewController {
if previousStatusBarStyle == -1 {
previousStatusBarStyle = UIApplication.shared.statusBarStyle.rawValue
}
let browserOptions = InAppBrowserOptions()
let _ = browserOptions.parse(options: options)
let browserSettings = InAppBrowserSettings()
let _ = browserSettings.parse(settings: settings)
let webViewOptions = InAppWebViewOptions()
let _ = webViewOptions.parse(options: options)
let webViewSettings = InAppWebViewSettings()
let _ = webViewSettings.parse(settings: settings)
let webViewController = InAppBrowserWebViewController()
webViewController.browserOptions = browserOptions
webViewController.webViewOptions = webViewOptions
webViewController.browserSettings = browserSettings
webViewController.webViewSettings = webViewSettings
webViewController.previousStatusBarStyle = previousStatusBarStyle
return webViewController
}
@ -76,13 +76,13 @@ public class InAppBrowserManager: NSObject, FlutterPlugin {
let mimeType = arguments["mimeType"] as? String
let encoding = arguments["encoding"] as? String
let baseUrl = arguments["baseUrl"] as? String
let options = arguments["options"] as! [String: Any?]
let settings = arguments["settings"] as! [String: Any?]
let contextMenu = arguments["contextMenu"] as! [String: Any]
let windowId = arguments["windowId"] as? Int64
let initialUserScripts = arguments["initialUserScripts"] as? [[String: Any]]
let pullToRefreshInitialOptions = arguments["pullToRefreshOptions"] as! [String: Any?]
let webViewController = prepareInAppBrowserWebViewController(options: options)
let webViewController = prepareInAppBrowserWebViewController(settings: settings)
webViewController.id = id
webViewController.initialUrlRequest = urlRequest != nil ? URLRequest.init(fromPluginMap: urlRequest!) : nil
@ -117,7 +117,7 @@ public class InAppBrowserManager: NSObject, FlutterPlugin {
navController.tmpWindow = tmpWindow
var animated = true
if let browserOptions = webViewController.browserOptions, browserOptions.hidden {
if let browserOptions = webViewController.browserSettings, browserOptions.hidden {
tmpWindow.isHidden = true
UIApplication.shared.delegate?.window??.makeKeyAndVisible()
animated = false

View File

@ -8,7 +8,7 @@
import Foundation
@objcMembers
public class InAppBrowserSettings: Options<InAppBrowserWebViewController> {
public class InAppBrowserSettings: IWebViewSettings<InAppBrowserWebViewController> {
var hidden = false
var hideToolbarTop = true
@ -32,7 +32,7 @@ public class InAppBrowserSettings: Options<InAppBrowserWebViewController> {
super.init()
}
override func getRealOptions(obj: InAppBrowserWebViewController?) -> [String: Any?] {
override func getRealSettings(obj: InAppBrowserWebViewController?) -> [String: Any?] {
var realOptions: [String: Any?] = toMap()
if let inAppBrowserWebViewController = obj {
realOptions["hideUrlBar"] = inAppBrowserWebViewController.searchBar.isHidden

View File

@ -28,8 +28,8 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
var initialUrlRequest: URLRequest?
var initialFile: String?
var contextMenu: [String: Any]?
var browserOptions: InAppBrowserOptions?
var webViewOptions: InAppWebViewOptions?
var browserSettings: InAppBrowserSettings?
var webViewSettings: InAppWebViewSettings?
var initialData: String?
var initialMimeType: String?
var initialEncoding: String?
@ -47,7 +47,7 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
userScripts.append(UserScript.fromMap(map: intialUserScript, windowId: windowId)!)
}
let preWebviewConfiguration = InAppWebView.preWKWebViewConfiguration(options: webViewOptions)
let preWebviewConfiguration = InAppWebView.preWKWebViewConfiguration(options: webViewSettings)
if let wId = windowId, let webViewTransport = InAppWebView.windowWebViews[wId] {
webView = webViewTransport.webView
webView.contextMenu = contextMenu
@ -67,7 +67,7 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
let pullToRefreshLayoutChannel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_inappwebview_pull_to_refresh_" + id,
binaryMessenger: SwiftFlutterPlugin.instance!.registrar!.messenger())
let pullToRefreshOptions = PullToRefreshOptions()
let pullToRefreshOptions = PullToRefreshSettings()
let _ = pullToRefreshOptions.parse(options: pullToRefreshInitialOptions)
let pullToRefreshControl = PullToRefreshControl(channel: pullToRefreshLayoutChannel, options: pullToRefreshOptions)
webView.pullToRefreshControl = pullToRefreshControl
@ -118,7 +118,7 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
webView.load(webViewTransport.request)
} else {
if #available(iOS 11.0, *) {
if let contentBlockers = webView.options?.contentBlockers, contentBlockers.count > 0 {
if let contentBlockers = webView.settings?.contentBlockers, contentBlockers.count > 0 {
do {
let jsonData = try JSONSerialization.data(withJSONObject: contentBlockers, options: [])
let blockRules = String(data: jsonData, encoding: String.Encoding.utf8)
@ -159,7 +159,7 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
else if let initialData = initialData {
let baseUrl = URL(string: initialBaseUrl!)!
var allowingReadAccessToURL: URL? = nil
if let allowingReadAccessTo = webView?.options?.allowingReadAccessTo, baseUrl.scheme == "file" {
if let allowingReadAccessTo = webView?.settings?.allowingReadAccessTo, baseUrl.scheme == "file" {
allowingReadAccessToURL = URL(string: allowingReadAccessTo)
if allowingReadAccessToURL?.scheme != "file" {
allowingReadAccessToURL = nil
@ -169,7 +169,7 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
}
else if let initialUrlRequest = initialUrlRequest {
var allowingReadAccessToURL: URL? = nil
if let allowingReadAccessTo = webView.options?.allowingReadAccessTo, let url = initialUrlRequest.url, url.scheme == "file" {
if let allowingReadAccessTo = webView.settings?.allowingReadAccessTo, let url = initialUrlRequest.url, url.scheme == "file" {
allowingReadAccessToURL = URL(string: allowingReadAccessTo)
if allowingReadAccessToURL?.scheme != "file" {
allowingReadAccessToURL = nil
@ -194,14 +194,14 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
}
public func prepareNavigationControllerBeforeViewWillAppear() {
if let browserOptions = browserOptions {
if let browserOptions = browserSettings {
navigationController?.modalPresentationStyle = UIModalPresentationStyle(rawValue: browserOptions.presentationStyle)!
navigationController?.modalTransitionStyle = UIModalTransitionStyle(rawValue: browserOptions.transitionStyle)!
}
}
public func prepareWebView() {
webView.options = webViewOptions
webView.settings = webViewSettings
webView.prepare()
searchBar = UISearchBar()
@ -231,7 +231,7 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
toolbarItems = [backButton, spacer, forwardButton, spacer, shareButton, spacer, reloadButton]
if let browserOptions = browserOptions {
if let browserOptions = browserSettings {
if !browserOptions.hideToolbarTop {
navigationController?.navigationBar.isHidden = false
if browserOptions.hideUrlBar {
@ -426,14 +426,14 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
webView.goBackOrForward(steps: steps)
}
public func setOptions(newOptions: InAppBrowserOptions, newOptionsMap: [String: Any]) {
public func setSettings(newSettings: InAppBrowserSettings, newSettingsMap: [String: Any]) {
let newInAppWebViewOptions = InAppWebViewOptions()
let _ = newInAppWebViewOptions.parse(options: newOptionsMap)
self.webView.setOptions(newOptions: newInAppWebViewOptions, newOptionsMap: newOptionsMap)
let newInAppWebViewOptions = InAppWebViewSettings()
let _ = newInAppWebViewOptions.parse(options: newSettingsMap)
self.webView.setOptions(newSettings: newInAppWebViewOptions, newOptionsMap: newSettingsMap)
if newOptionsMap["hidden"] != nil, browserOptions?.hidden != newOptions.hidden {
if newOptions.hidden {
if newSettingsMap["hidden"] != nil, browserSettings?.hidden != newSettings.hidden {
if newSettings.hidden {
hide()
}
else {
@ -441,68 +441,68 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
}
}
if newOptionsMap["hideUrlBar"] != nil, browserOptions?.hideUrlBar != newOptions.hideUrlBar {
searchBar.isHidden = newOptions.hideUrlBar
if newSettingsMap["hideUrlBar"] != nil, browserSettings?.hideUrlBar != newSettings.hideUrlBar {
searchBar.isHidden = newSettings.hideUrlBar
}
if newOptionsMap["hideToolbarTop"] != nil, browserOptions?.hideToolbarTop != newOptions.hideToolbarTop {
navigationController?.navigationBar.isHidden = newOptions.hideToolbarTop
if newSettingsMap["hideToolbarTop"] != nil, browserSettings?.hideToolbarTop != newSettings.hideToolbarTop {
navigationController?.navigationBar.isHidden = newSettings.hideToolbarTop
}
if newOptionsMap["toolbarTopBackgroundColor"] != nil, browserOptions?.toolbarTopBackgroundColor != newOptions.toolbarTopBackgroundColor {
if let bgColor = newOptions.toolbarTopBackgroundColor, !bgColor.isEmpty {
if newSettingsMap["toolbarTopBackgroundColor"] != nil, browserSettings?.toolbarTopBackgroundColor != newSettings.toolbarTopBackgroundColor {
if let bgColor = newSettings.toolbarTopBackgroundColor, !bgColor.isEmpty {
navigationController?.navigationBar.backgroundColor = UIColor(hexString: bgColor)
} else {
navigationController?.navigationBar.backgroundColor = nil
}
}
if newOptionsMap["toolbarTopBarTintColor"] != nil, browserOptions?.toolbarTopBarTintColor != newOptions.toolbarTopBarTintColor {
if let barTintColor = newOptions.toolbarTopBarTintColor, !barTintColor.isEmpty {
if newSettingsMap["toolbarTopBarTintColor"] != nil, browserSettings?.toolbarTopBarTintColor != newSettings.toolbarTopBarTintColor {
if let barTintColor = newSettings.toolbarTopBarTintColor, !barTintColor.isEmpty {
navigationController?.navigationBar.barTintColor = UIColor(hexString: barTintColor)
} else {
navigationController?.navigationBar.barTintColor = nil
}
}
if newOptionsMap["toolbarTopTintColor"] != nil, browserOptions?.toolbarTopTintColor != newOptions.toolbarTopTintColor {
if let tintColor = newOptions.toolbarTopTintColor, !tintColor.isEmpty {
if newSettingsMap["toolbarTopTintColor"] != nil, browserSettings?.toolbarTopTintColor != newSettings.toolbarTopTintColor {
if let tintColor = newSettings.toolbarTopTintColor, !tintColor.isEmpty {
navigationController?.navigationBar.tintColor = UIColor(hexString: tintColor)
} else {
navigationController?.navigationBar.tintColor = nil
}
}
if newOptionsMap["hideToolbarBottom"] != nil, browserOptions?.hideToolbarBottom != newOptions.hideToolbarBottom {
if newSettingsMap["hideToolbarBottom"] != nil, browserSettings?.hideToolbarBottom != newSettings.hideToolbarBottom {
navigationController?.isToolbarHidden = !newOptions.hideToolbarBottom
}
if newOptionsMap["toolbarBottomBackgroundColor"] != nil, browserOptions?.toolbarBottomBackgroundColor != newOptions.toolbarBottomBackgroundColor {
if let bgColor = newOptions.toolbarBottomBackgroundColor, !bgColor.isEmpty {
if newSettingsMap["toolbarBottomBackgroundColor"] != nil, browserSettings?.toolbarBottomBackgroundColor != newSettings.toolbarBottomBackgroundColor {
if let bgColor = newSettings.toolbarBottomBackgroundColor, !bgColor.isEmpty {
navigationController?.toolbar.barTintColor = UIColor(hexString: bgColor)
} else {
navigationController?.toolbar.barTintColor = nil
}
}
if newOptionsMap["toolbarBottomTintColor"] != nil, browserOptions?.toolbarBottomTintColor != newOptions.toolbarBottomTintColor {
if let tintColor = newOptions.toolbarBottomTintColor, !tintColor.isEmpty {
if newSettingsMap["toolbarBottomTintColor"] != nil, browserSettings?.toolbarBottomTintColor != newSettings.toolbarBottomTintColor {
if let tintColor = newSettings.toolbarBottomTintColor, !tintColor.isEmpty {
navigationController?.toolbar.tintColor = UIColor(hexString: tintColor)
} else {
navigationController?.toolbar.tintColor = nil
}
}
if newOptionsMap["toolbarTopTranslucent"] != nil, browserOptions?.toolbarTopTranslucent != newOptions.toolbarTopTranslucent {
navigationController?.navigationBar.isTranslucent = newOptions.toolbarTopTranslucent
if newSettingsMap["toolbarTopTranslucent"] != nil, browserSettings?.toolbarTopTranslucent != newSettings.toolbarTopTranslucent {
navigationController?.navigationBar.isTranslucent = newSettings.toolbarTopTranslucent
}
if newOptionsMap["toolbarBottomTranslucent"] != nil, browserOptions?.toolbarBottomTranslucent != newOptions.toolbarBottomTranslucent {
navigationController?.toolbar.isTranslucent = newOptions.toolbarBottomTranslucent
if newSettingsMap["toolbarBottomTranslucent"] != nil, browserSettings?.toolbarBottomTranslucent != newSettings.toolbarBottomTranslucent {
navigationController?.toolbar.isTranslucent = newSettings.toolbarBottomTranslucent
}
if newOptionsMap["closeButtonCaption"] != nil, browserOptions?.closeButtonCaption != newOptions.closeButtonCaption {
if let closeButtonCaption = newOptions.closeButtonCaption, !closeButtonCaption.isEmpty {
if newSettingsMap["closeButtonCaption"] != nil, browserSettings?.closeButtonCaption != newSettings.closeButtonCaption {
if let closeButtonCaption = newSettings.closeButtonCaption, !closeButtonCaption.isEmpty {
if let oldTitle = closeButton.title, !oldTitle.isEmpty {
closeButton.title = closeButtonCaption
} else {
@ -515,38 +515,38 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
}
}
if newOptionsMap["closeButtonColor"] != nil, browserOptions?.closeButtonColor != newOptions.closeButtonColor {
if let tintColor = newOptions.closeButtonColor, !tintColor.isEmpty {
if newSettingsMap["closeButtonColor"] != nil, browserSettings?.closeButtonColor != newSettings.closeButtonColor {
if let tintColor = newSettings.closeButtonColor, !tintColor.isEmpty {
closeButton.tintColor = UIColor(hexString: tintColor)
} else {
closeButton.tintColor = nil
}
}
if newOptionsMap["presentationStyle"] != nil, browserOptions?.presentationStyle != newOptions.presentationStyle {
navigationController?.modalPresentationStyle = UIModalPresentationStyle(rawValue: newOptions.presentationStyle)!
if newSettingsMap["presentationStyle"] != nil, browserSettings?.presentationStyle != newSettings.presentationStyle {
navigationController?.modalPresentationStyle = UIModalPresentationStyle(rawValue: newSettings.presentationStyle)!
}
if newOptionsMap["transitionStyle"] != nil, browserOptions?.transitionStyle != newOptions.transitionStyle {
navigationController?.modalTransitionStyle = UIModalTransitionStyle(rawValue: newOptions.transitionStyle)!
if newSettingsMap["transitionStyle"] != nil, browserSettings?.transitionStyle != newSettings.transitionStyle {
navigationController?.modalTransitionStyle = UIModalTransitionStyle(rawValue: newSettings.transitionStyle)!
}
if newOptionsMap["hideProgressBar"] != nil, browserOptions?.hideProgressBar != newOptions.hideProgressBar {
progressBar.isHidden = newOptions.hideProgressBar
if newSettingsMap["hideProgressBar"] != nil, browserSettings?.hideProgressBar != newSettings.hideProgressBar {
progressBar.isHidden = newSettings.hideProgressBar
}
self.browserOptions = newOptions
self.webViewOptions = newInAppWebViewOptions
self.browserSettings = newSettings
self.webViewSettings = newInAppWebViewOptions
}
public func getOptions() -> [String: Any?]? {
let webViewOptionsMap = self.webView.getOptions()
if (self.browserOptions == nil || webViewOptionsMap == nil) {
public func getSettings() -> [String: Any?]? {
let webViewSettingsMap = self.webView.getSettings()
if (self.browserSettings == nil || webViewSettingsMap == nil) {
return nil
}
var optionsMap = self.browserOptions!.getRealOptions(obj: self)
optionsMap.merge(webViewOptionsMap!, uniquingKeysWith: { (current, _) in current })
return optionsMap
var settingsMap = self.browserSettings!.getRealSettings(obj: self)
settingsMap.merge(webViewSettingsMap!, uniquingKeysWith: { (current, _) in current })
return settingsMap
}
public func dispose() {

View File

@ -29,7 +29,7 @@ public class FlutterWebViewController: NSObject, FlutterPlatformView {
myView = UIView(frame: frame)
myView!.clipsToBounds = true
let initialOptions = params["initialOptions"] as! [String: Any?]
let initialSettings = params["initialSettings"] as! [String: Any?]
let contextMenu = params["contextMenu"] as? [String: Any]
let windowId = params["windowId"] as? Int64
let initialUserScripts = params["initialUserScripts"] as? [[String: Any]]
@ -42,9 +42,9 @@ public class FlutterWebViewController: NSObject, FlutterPlatformView {
}
}
let options = InAppWebViewOptions()
let _ = options.parse(options: initialOptions)
let preWebviewConfiguration = InAppWebView.preWKWebViewConfiguration(options: options)
let settings = InAppWebViewSettings()
let _ = settings.parse(settings: initialSettings)
let preWebviewConfiguration = InAppWebView.preWKWebViewConfiguration(options: settings)
if let wId = windowId, let webViewTransport = InAppWebView.windowWebViews[wId] {
webView = webViewTransport.webView
@ -65,8 +65,8 @@ public class FlutterWebViewController: NSObject, FlutterPlatformView {
let pullToRefreshLayoutChannel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_inappwebview_pull_to_refresh_" + String(describing: viewId),
binaryMessenger: registrar.messenger())
let pullToRefreshOptions = PullToRefreshOptions()
let _ = pullToRefreshOptions.parse(options: pullToRefreshInitialOptions)
let pullToRefreshOptions = PullToRefreshSettings()
let _ = pullToRefreshOptions.parse(settings: pullToRefreshInitialOptions)
let pullToRefreshControl = PullToRefreshControl(channel: pullToRefreshLayoutChannel, options: pullToRefreshOptions)
webView!.pullToRefreshControl = pullToRefreshControl
pullToRefreshControl.delegate = webView!
@ -77,7 +77,7 @@ public class FlutterWebViewController: NSObject, FlutterPlatformView {
myView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
myView!.addSubview(webView!)
webView!.options = options
webView!.settings = settings
webView!.prepare()
webView!.windowCreated = true
}
@ -95,7 +95,7 @@ public class FlutterWebViewController: NSObject, FlutterPlatformView {
if windowId == nil {
if #available(iOS 11.0, *) {
self.webView!.configuration.userContentController.removeAllContentRuleLists()
if let contentBlockers = webView!.options?.contentBlockers, contentBlockers.count > 0 {
if let contentBlockers = webView!.settings?.contentBlockers, contentBlockers.count > 0 {
do {
let jsonData = try JSONSerialization.data(withJSONObject: contentBlockers, options: [])
let blockRules = String(data: jsonData, encoding: String.Encoding.utf8)
@ -141,7 +141,7 @@ public class FlutterWebViewController: NSObject, FlutterPlatformView {
let encoding = initialData["encoding"]!
let baseUrl = URL(string: initialData["baseUrl"]!)!
var allowingReadAccessToURL: URL? = nil
if let allowingReadAccessTo = webView?.options?.allowingReadAccessTo, baseUrl.scheme == "file" {
if let allowingReadAccessTo = webView?.settings?.allowingReadAccessTo, baseUrl.scheme == "file" {
allowingReadAccessToURL = URL(string: allowingReadAccessTo)
if allowingReadAccessToURL?.scheme != "file" {
allowingReadAccessToURL = nil
@ -152,7 +152,7 @@ public class FlutterWebViewController: NSObject, FlutterPlatformView {
else if let initialUrlRequest = initialUrlRequest {
let urlRequest = URLRequest.init(fromPluginMap: initialUrlRequest)
var allowingReadAccessToURL: URL? = nil
if let allowingReadAccessTo = webView?.options?.allowingReadAccessTo, let url = urlRequest.url, url.scheme == "file" {
if let allowingReadAccessTo = webView?.settings?.allowingReadAccessTo, let url = urlRequest.url, url.scheme == "file" {
allowingReadAccessToURL = URL(string: allowingReadAccessTo)
if allowingReadAccessToURL?.scheme != "file" {
allowingReadAccessToURL = nil

View File

@ -15,7 +15,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
var windowCreated = false
var inAppBrowserDelegate: InAppBrowserDelegate?
var channel: FlutterMethodChannel?
var options: InAppWebViewOptions?
var settings: InAppWebViewSettings?
var pullToRefreshControl: PullToRefreshControl?
var webMessageChannels: [String:WebMessageChannel] = [:]
var webMessageListeners: [WebMessageListener] = []
@ -148,7 +148,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
if sender == recognizerForDisablingContextMenuOnLinks,
let options = options, !options.disableLongPressContextMenuOnLinks {
let settings = settings, !settings.disableLongPressContextMenuOnLinks {
return
}
@ -231,7 +231,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if let _ = sender as? UIMenuController {
if self.options?.disableContextMenu == true {
if self.settings?.disableContextMenu == true {
if !onCreateContextMenuEventTriggeredWhenMenuDisabled {
// workaround to trigger onCreateContextMenu event as the same on Android
self.onCreateContextMenu()
@ -246,7 +246,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
if let menu = contextMenu {
let contextMenuOptions = ContextMenuOptions()
if let contextMenuOptionsMap = menu["options"] as? [String: Any?] {
let _ = contextMenuOptions.parse(options: contextMenuOptionsMap)
let _ = contextMenuOptions.parse(settings: contextMenuOptionsMap)
if !action.description.starts(with: "onContextMenuActionItemClicked-") && contextMenuOptions.hideDefaultSystemContextMenuItems {
return false
}
@ -326,15 +326,15 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
name: UIWindow.didBecomeHiddenNotification,
object: window)
if let options = options {
if options.transparentBackground {
if let settings = settings {
if settings.transparentBackground {
isOpaque = false
backgroundColor = UIColor.clear
scrollView.backgroundColor = UIColor.clear
}
// prevent webView from bouncing
if options.disallowOverScroll {
if settings.disallowOverScroll {
if responds(to: #selector(getter: scrollView)) {
scrollView.bounces = false
}
@ -348,47 +348,47 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
if #available(iOS 11.0, *) {
accessibilityIgnoresInvertColors = options.accessibilityIgnoresInvertColors
accessibilityIgnoresInvertColors = settings.accessibilityIgnoresInvertColors
scrollView.contentInsetAdjustmentBehavior =
UIScrollView.ContentInsetAdjustmentBehavior.init(rawValue: options.contentInsetAdjustmentBehavior)!
UIScrollView.ContentInsetAdjustmentBehavior.init(rawValue: settings.contentInsetAdjustmentBehavior)!
}
allowsBackForwardNavigationGestures = options.allowsBackForwardNavigationGestures
allowsBackForwardNavigationGestures = settings.allowsBackForwardNavigationGestures
if #available(iOS 9.0, *) {
allowsLinkPreview = options.allowsLinkPreview
if !options.userAgent.isEmpty {
customUserAgent = options.userAgent
allowsLinkPreview = settings.allowsLinkPreview
if !settings.userAgent.isEmpty {
customUserAgent = settings.userAgent
}
}
if #available(iOS 13.0, *) {
scrollView.automaticallyAdjustsScrollIndicatorInsets = options.automaticallyAdjustsScrollIndicatorInsets
scrollView.automaticallyAdjustsScrollIndicatorInsets = settings.automaticallyAdjustsScrollIndicatorInsets
}
scrollView.showsVerticalScrollIndicator = !options.disableVerticalScroll
scrollView.showsHorizontalScrollIndicator = !options.disableHorizontalScroll
scrollView.showsVerticalScrollIndicator = options.verticalScrollBarEnabled
scrollView.showsHorizontalScrollIndicator = options.horizontalScrollBarEnabled
scrollView.isScrollEnabled = !(options.disableVerticalScroll && options.disableHorizontalScroll)
scrollView.isDirectionalLockEnabled = options.isDirectionalLockEnabled
scrollView.showsVerticalScrollIndicator = !settings.disableVerticalScroll
scrollView.showsHorizontalScrollIndicator = !settings.disableHorizontalScroll
scrollView.showsVerticalScrollIndicator = settings.verticalScrollBarEnabled
scrollView.showsHorizontalScrollIndicator = settings.horizontalScrollBarEnabled
scrollView.isScrollEnabled = !(settings.disableVerticalScroll && settings.disableHorizontalScroll)
scrollView.isDirectionalLockEnabled = settings.isDirectionalLockEnabled
scrollView.decelerationRate = Util.getDecelerationRate(type: options.decelerationRate)
scrollView.alwaysBounceVertical = options.alwaysBounceVertical
scrollView.alwaysBounceHorizontal = options.alwaysBounceHorizontal
scrollView.scrollsToTop = options.scrollsToTop
scrollView.isPagingEnabled = options.isPagingEnabled
scrollView.maximumZoomScale = CGFloat(options.maximumZoomScale)
scrollView.minimumZoomScale = CGFloat(options.minimumZoomScale)
scrollView.decelerationRate = Util.getDecelerationRate(type: settings.decelerationRate)
scrollView.alwaysBounceVertical = settings.alwaysBounceVertical
scrollView.alwaysBounceHorizontal = settings.alwaysBounceHorizontal
scrollView.scrollsToTop = settings.scrollsToTop
scrollView.isPagingEnabled = settings.isPagingEnabled
scrollView.maximumZoomScale = CGFloat(settings.maximumZoomScale)
scrollView.minimumZoomScale = CGFloat(settings.minimumZoomScale)
if #available(iOS 14.0, *) {
mediaType = options.mediaType
pageZoom = CGFloat(options.pageZoom)
mediaType = settings.mediaType
pageZoom = CGFloat(settings.pageZoom)
}
// debugging is always enabled for iOS,
// there isn't any option to set about it such as on Android.
if options.clearCache {
if settings.clearCache {
clearCache()
}
}
@ -403,23 +403,23 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
configuration.preferences = WKPreferences()
if let options = options {
if let settings = settings {
if #available(iOS 9.0, *) {
configuration.allowsAirPlayForMediaPlayback = options.allowsAirPlayForMediaPlayback
configuration.allowsPictureInPictureMediaPlayback = options.allowsPictureInPictureMediaPlayback
configuration.allowsAirPlayForMediaPlayback = settings.allowsAirPlayForMediaPlayback
configuration.allowsPictureInPictureMediaPlayback = settings.allowsPictureInPictureMediaPlayback
}
configuration.preferences.javaScriptCanOpenWindowsAutomatically = options.javaScriptCanOpenWindowsAutomatically
configuration.preferences.minimumFontSize = CGFloat(options.minimumFontSize)
configuration.preferences.javaScriptCanOpenWindowsAutomatically = settings.javaScriptCanOpenWindowsAutomatically
configuration.preferences.minimumFontSize = CGFloat(settings.minimumFontSize)
if #available(iOS 13.0, *) {
configuration.preferences.isFraudulentWebsiteWarningEnabled = options.isFraudulentWebsiteWarningEnabled
configuration.defaultWebpagePreferences.preferredContentMode = WKWebpagePreferences.ContentMode(rawValue: options.preferredContentMode)!
configuration.preferences.isFraudulentWebsiteWarningEnabled = settings.isFraudulentWebsiteWarningEnabled
configuration.defaultWebpagePreferences.preferredContentMode = WKWebpagePreferences.ContentMode(rawValue: settings.preferredContentMode)!
}
configuration.preferences.javaScriptEnabled = options.javaScriptEnabled
configuration.preferences.javaScriptEnabled = settings.javaScriptEnabled
if #available(iOS 14.0, *) {
configuration.defaultWebpagePreferences.allowsContentJavaScript = options.javaScriptEnabled
configuration.defaultWebpagePreferences.allowsContentJavaScript = settings.javaScriptEnabled
}
}
}
@ -434,7 +434,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
configuration.userContentController = WKUserContentController()
configuration.userContentController.initialize()
if let applePayAPIEnabled = options?.applePayAPIEnabled, applePayAPIEnabled {
if let applePayAPIEnabled = settings?.applePayAPIEnabled, applePayAPIEnabled {
return
}
@ -448,19 +448,19 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
configuration.userContentController.addPluginScript(LAST_TOUCHED_ANCHOR_OR_IMAGE_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(FIND_TEXT_HIGHLIGHT_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(ORIGINAL_VIEWPORT_METATAG_CONTENT_JS_PLUGIN_SCRIPT)
if let options = options {
if options.useShouldInterceptAjaxRequest {
if let settings = settings {
if settings.useShouldInterceptAjaxRequest {
configuration.userContentController.addPluginScript(INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT)
}
if options.useShouldInterceptFetchRequest {
if settings.useShouldInterceptFetchRequest {
configuration.userContentController.addPluginScript(INTERCEPT_FETCH_REQUEST_JS_PLUGIN_SCRIPT)
}
if options.useOnLoadResource {
if settings.useOnLoadResource {
configuration.userContentController.addPluginScript(ON_LOAD_RESOURCE_JS_PLUGIN_SCRIPT)
}
if !options.supportZoom {
if !settings.supportZoom {
configuration.userContentController.addPluginScript(NOT_SUPPORT_ZOOM_JS_PLUGIN_SCRIPT)
} else if options.enableViewportScale {
} else if settings.enableViewportScale {
configuration.userContentController.addPluginScript(ENABLE_VIEWPORT_SCALE_JS_PLUGIN_SCRIPT)
}
}
@ -474,64 +474,64 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
configuration.userContentController.sync(scriptMessageHandler: self)
}
public static func preWKWebViewConfiguration(options: InAppWebViewOptions?) -> WKWebViewConfiguration {
public static func preWKWebViewConfiguration(settings: InAppWebViewSettings?) -> WKWebViewConfiguration {
let configuration = WKWebViewConfiguration()
configuration.processPool = WKProcessPoolManager.sharedProcessPool
if let options = options {
configuration.allowsInlineMediaPlayback = options.allowsInlineMediaPlayback
configuration.suppressesIncrementalRendering = options.suppressesIncrementalRendering
configuration.selectionGranularity = WKSelectionGranularity.init(rawValue: options.selectionGranularity)!
if let settings = settings {
configuration.allowsInlineMediaPlayback = settings.allowsInlineMediaPlayback
configuration.suppressesIncrementalRendering = settings.suppressesIncrementalRendering
configuration.selectionGranularity = WKSelectionGranularity.init(rawValue: settings.selectionGranularity)!
if options.allowUniversalAccessFromFileURLs {
configuration.setValue(options.allowUniversalAccessFromFileURLs, forKey: "allowUniversalAccessFromFileURLs")
if settings.allowUniversalAccessFromFileURLs {
configuration.setValue(settings.allowUniversalAccessFromFileURLs, forKey: "allowUniversalAccessFromFileURLs")
}
if options.allowFileAccessFromFileURLs {
configuration.preferences.setValue(options.allowFileAccessFromFileURLs, forKey: "allowFileAccessFromFileURLs")
if settings.allowFileAccessFromFileURLs {
configuration.preferences.setValue(settings.allowFileAccessFromFileURLs, forKey: "allowFileAccessFromFileURLs")
}
if #available(iOS 9.0, *) {
if options.incognito {
if settings.incognito {
configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
} else if options.cacheEnabled {
} else if settings.cacheEnabled {
configuration.websiteDataStore = WKWebsiteDataStore.default()
}
if !options.applicationNameForUserAgent.isEmpty {
if !settings.applicationNameForUserAgent.isEmpty {
if let applicationNameForUserAgent = configuration.applicationNameForUserAgent {
configuration.applicationNameForUserAgent = applicationNameForUserAgent + " " + options.applicationNameForUserAgent
configuration.applicationNameForUserAgent = applicationNameForUserAgent + " " + settings.applicationNameForUserAgent
}
}
}
if #available(iOS 10.0, *) {
configuration.ignoresViewportScaleLimits = options.ignoresViewportScaleLimits
configuration.ignoresViewportScaleLimits = settings.ignoresViewportScaleLimits
var dataDetectorTypes = WKDataDetectorTypes.init(rawValue: 0)
for type in options.dataDetectorTypes {
for type in settings.dataDetectorTypes {
let dataDetectorType = Util.getDataDetectorType(type: type)
dataDetectorTypes = WKDataDetectorTypes(rawValue: dataDetectorTypes.rawValue | dataDetectorType.rawValue)
}
configuration.dataDetectorTypes = dataDetectorTypes
configuration.mediaTypesRequiringUserActionForPlayback = options.mediaPlaybackRequiresUserGesture ? .all : []
configuration.mediaTypesRequiringUserActionForPlayback = settings.mediaPlaybackRequiresUserGesture ? .all : []
} else {
// Fallback on earlier versions
configuration.mediaPlaybackRequiresUserAction = options.mediaPlaybackRequiresUserGesture
configuration.mediaPlaybackRequiresUserAction = settings.mediaPlaybackRequiresUserGesture
}
if #available(iOS 11.0, *) {
for scheme in options.resourceCustomSchemes {
for scheme in settings.resourceCustomSchemes {
configuration.setURLSchemeHandler(CustomeSchemeHandler(), forURLScheme: scheme)
}
if options.sharedCookiesEnabled {
if settings.sharedCookiesEnabled {
// More info to sending cookies with WKWebView
// https://stackoverflow.com/questions/26573137/can-i-set-the-cookies-to-be-used-by-a-wkwebview/26577303#26577303
// Set Cookies in iOS 11 and above, initialize websiteDataStore before setting cookies
// See also https://forums.developer.apple.com/thread/97194
// check if websiteDataStore has not been initialized before
if(!options.incognito && !options.cacheEnabled) {
if(!settings.incognito && !settings.cacheEnabled) {
configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
}
for cookie in HTTPCookieStorage.shared.cookies ?? [] {
@ -541,7 +541,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
if #available(iOS 14.0, *) {
configuration.limitsNavigationsToAppBoundDomains = options.limitsNavigationsToAppBoundDomains
configuration.limitsNavigationsToAppBoundDomains = settings.limitsNavigationsToAppBoundDomains
}
}
@ -663,7 +663,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
if let snapshotWidth = with["snapshotWidth"] as? Double {
snapshotConfiguration!.snapshotWidth = NSNumber(value: snapshotWidth)
}
if #available(iOS 13.0, *), let afterScreenUpdates = with["iosAfterScreenUpdates"] as? Bool {
if #available(iOS 13.0, *), let afterScreenUpdates = with["afterScreenUpdates"] as? Bool {
snapshotConfiguration!.afterScreenUpdates = afterScreenUpdates
}
}
@ -802,15 +802,15 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
loadUrl(urlRequest: urlRequest, allowingReadAccessTo: nil)
}
func setOptions(newOptions: InAppWebViewOptions, newOptionsMap: [String: Any]) {
func setSettings(newSettings: InAppWebViewSettings, newSettingsMap: [String: Any]) {
// MUST be the first! In this way, all the options that uses evaluateJavaScript can be applied/blocked!
// MUST be the first! In this way, all the settings that uses evaluateJavaScript can be applied/blocked!
if #available(iOS 13.0, *) {
if newOptionsMap["applePayAPIEnabled"] != nil && options?.applePayAPIEnabled != newOptions.applePayAPIEnabled {
if let options = options {
options.applePayAPIEnabled = newOptions.applePayAPIEnabled
if newSettingsMap["applePayAPIEnabled"] != nil && settings?.applePayAPIEnabled != newSettings.applePayAPIEnabled {
if let settings = settings {
settings.applePayAPIEnabled = newSettings.applePayAPIEnabled
}
if !newOptions.applePayAPIEnabled {
if !newSettings.applePayAPIEnabled {
// re-add WKUserScripts for the next page load
prepareAndAddUserScripts()
} else {
@ -819,8 +819,8 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
}
if newOptionsMap["transparentBackground"] != nil && options?.transparentBackground != newOptions.transparentBackground {
if newOptions.transparentBackground {
if newSettingsMap["transparentBackground"] != nil && settings?.transparentBackground != newSettings.transparentBackground {
if newSettings.transparentBackground {
isOpaque = false
backgroundColor = UIColor.clear
scrollView.backgroundColor = UIColor.clear
@ -831,47 +831,47 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
}
if newOptionsMap["disallowOverScroll"] != nil && options?.disallowOverScroll != newOptions.disallowOverScroll {
if newSettingsMap["disallowOverScroll"] != nil && settings?.disallowOverScroll != newSettings.disallowOverScroll {
if responds(to: #selector(getter: scrollView)) {
scrollView.bounces = !newOptions.disallowOverScroll
scrollView.bounces = !newSettings.disallowOverScroll
}
else {
for subview: UIView in subviews {
if subview is UIScrollView {
(subview as! UIScrollView).bounces = !newOptions.disallowOverScroll
(subview as! UIScrollView).bounces = !newSettings.disallowOverScroll
}
}
}
}
if #available(iOS 9.0, *) {
if (newOptionsMap["incognito"] != nil && options?.incognito != newOptions.incognito && newOptions.incognito) {
if (newSettingsMap["incognito"] != nil && settings?.incognito != newSettings.incognito && newSettings.incognito) {
configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
} else if (newOptionsMap["cacheEnabled"] != nil && options?.cacheEnabled != newOptions.cacheEnabled && newOptions.cacheEnabled) {
} else if (newSettingsMap["cacheEnabled"] != nil && settings?.cacheEnabled != newSettings.cacheEnabled && newSettings.cacheEnabled) {
configuration.websiteDataStore = WKWebsiteDataStore.default()
}
}
if #available(iOS 11.0, *) {
if (newOptionsMap["sharedCookiesEnabled"] != nil && options?.sharedCookiesEnabled != newOptions.sharedCookiesEnabled && newOptions.sharedCookiesEnabled) {
if(!newOptions.incognito && !newOptions.cacheEnabled) {
if (newSettingsMap["sharedCookiesEnabled"] != nil && settings?.sharedCookiesEnabled != newSettings.sharedCookiesEnabled && newSettings.sharedCookiesEnabled) {
if(!newSettings.incognito && !newSettings.cacheEnabled) {
configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
}
for cookie in HTTPCookieStorage.shared.cookies ?? [] {
configuration.websiteDataStore.httpCookieStore.setCookie(cookie, completionHandler: nil)
}
}
if newOptionsMap["accessibilityIgnoresInvertColors"] != nil && options?.accessibilityIgnoresInvertColors != newOptions.accessibilityIgnoresInvertColors {
accessibilityIgnoresInvertColors = newOptions.accessibilityIgnoresInvertColors
if newSettingsMap["accessibilityIgnoresInvertColors"] != nil && settings?.accessibilityIgnoresInvertColors != newSettings.accessibilityIgnoresInvertColors {
accessibilityIgnoresInvertColors = newSettings.accessibilityIgnoresInvertColors
}
if newOptionsMap["contentInsetAdjustmentBehavior"] != nil && options?.contentInsetAdjustmentBehavior != newOptions.contentInsetAdjustmentBehavior {
if newSettingsMap["contentInsetAdjustmentBehavior"] != nil && settings?.contentInsetAdjustmentBehavior != newSettings.contentInsetAdjustmentBehavior {
scrollView.contentInsetAdjustmentBehavior =
UIScrollView.ContentInsetAdjustmentBehavior.init(rawValue: newOptions.contentInsetAdjustmentBehavior)!
UIScrollView.ContentInsetAdjustmentBehavior.init(rawValue: newSettings.contentInsetAdjustmentBehavior)!
}
}
if newOptionsMap["enableViewportScale"] != nil && options?.enableViewportScale != newOptions.enableViewportScale {
if !newOptions.enableViewportScale {
if newSettingsMap["enableViewportScale"] != nil && settings?.enableViewportScale != newSettings.enableViewportScale {
if !newSettings.enableViewportScale {
if configuration.userContentController.userScripts.contains(ENABLE_VIEWPORT_SCALE_JS_PLUGIN_SCRIPT) {
configuration.userContentController.removePluginScript(ENABLE_VIEWPORT_SCALE_JS_PLUGIN_SCRIPT)
evaluateJavaScript(NOT_ENABLE_VIEWPORT_SCALE_JS_SOURCE)
@ -882,8 +882,8 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
}
if newOptionsMap["supportZoom"] != nil && options?.supportZoom != newOptions.supportZoom {
if newOptions.supportZoom {
if newSettingsMap["supportZoom"] != nil && settings?.supportZoom != newSettings.supportZoom {
if newSettings.supportZoom {
if configuration.userContentController.userScripts.contains(NOT_SUPPORT_ZOOM_JS_PLUGIN_SCRIPT) {
configuration.userContentController.removePluginScript(NOT_SUPPORT_ZOOM_JS_PLUGIN_SCRIPT)
evaluateJavaScript(SUPPORT_ZOOM_JS_SOURCE)
@ -894,77 +894,77 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
}
if newOptionsMap["useOnLoadResource"] != nil && options?.useOnLoadResource != newOptions.useOnLoadResource {
if let applePayAPIEnabled = options?.applePayAPIEnabled, !applePayAPIEnabled {
if newSettingsMap["useOnLoadResource"] != nil && settings?.useOnLoadResource != newSettings.useOnLoadResource {
if let applePayAPIEnabled = settings?.applePayAPIEnabled, !applePayAPIEnabled {
enablePluginScriptAtRuntime(flagVariable: FLAG_VARIABLE_FOR_ON_LOAD_RESOURCE_JS_SOURCE,
enable: newOptions.useOnLoadResource,
enable: newSettings.useOnLoadResource,
pluginScript: ON_LOAD_RESOURCE_JS_PLUGIN_SCRIPT)
} else {
newOptions.useOnLoadResource = false
newSettings.useOnLoadResource = false
}
}
if newOptionsMap["useShouldInterceptAjaxRequest"] != nil && options?.useShouldInterceptAjaxRequest != newOptions.useShouldInterceptAjaxRequest {
if let applePayAPIEnabled = options?.applePayAPIEnabled, !applePayAPIEnabled {
if newSettingsMap["useShouldInterceptAjaxRequest"] != nil && settings?.useShouldInterceptAjaxRequest != newSettings.useShouldInterceptAjaxRequest {
if let applePayAPIEnabled = settings?.applePayAPIEnabled, !applePayAPIEnabled {
enablePluginScriptAtRuntime(flagVariable: FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE,
enable: newOptions.useShouldInterceptAjaxRequest,
enable: newSettings.useShouldInterceptAjaxRequest,
pluginScript: INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT)
} else {
newOptions.useShouldInterceptFetchRequest = false
newSettings.useShouldInterceptFetchRequest = false
}
}
if newOptionsMap["useShouldInterceptFetchRequest"] != nil && options?.useShouldInterceptFetchRequest != newOptions.useShouldInterceptFetchRequest {
if let applePayAPIEnabled = options?.applePayAPIEnabled, !applePayAPIEnabled {
if newSettingsMap["useShouldInterceptFetchRequest"] != nil && settings?.useShouldInterceptFetchRequest != newSettings.useShouldInterceptFetchRequest {
if let applePayAPIEnabled = settings?.applePayAPIEnabled, !applePayAPIEnabled {
enablePluginScriptAtRuntime(flagVariable: FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_FETCH_REQUEST_JS_SOURCE,
enable: newOptions.useShouldInterceptFetchRequest,
enable: newSettings.useShouldInterceptFetchRequest,
pluginScript: INTERCEPT_FETCH_REQUEST_JS_PLUGIN_SCRIPT)
} else {
newOptions.useShouldInterceptFetchRequest = false
newSettings.useShouldInterceptFetchRequest = false
}
}
if newOptionsMap["mediaPlaybackRequiresUserGesture"] != nil && options?.mediaPlaybackRequiresUserGesture != newOptions.mediaPlaybackRequiresUserGesture {
if newSettingsMap["mediaPlaybackRequiresUserGesture"] != nil && settings?.mediaPlaybackRequiresUserGesture != newSettings.mediaPlaybackRequiresUserGesture {
if #available(iOS 10.0, *) {
configuration.mediaTypesRequiringUserActionForPlayback = (newOptions.mediaPlaybackRequiresUserGesture) ? .all : []
configuration.mediaTypesRequiringUserActionForPlayback = (newSettings.mediaPlaybackRequiresUserGesture) ? .all : []
} else {
// Fallback on earlier versions
configuration.mediaPlaybackRequiresUserAction = newOptions.mediaPlaybackRequiresUserGesture
configuration.mediaPlaybackRequiresUserAction = newSettings.mediaPlaybackRequiresUserGesture
}
}
if newOptionsMap["allowsInlineMediaPlayback"] != nil && options?.allowsInlineMediaPlayback != newOptions.allowsInlineMediaPlayback {
configuration.allowsInlineMediaPlayback = newOptions.allowsInlineMediaPlayback
if newSettingsMap["allowsInlineMediaPlayback"] != nil && settings?.allowsInlineMediaPlayback != newSettings.allowsInlineMediaPlayback {
configuration.allowsInlineMediaPlayback = newSettings.allowsInlineMediaPlayback
}
if newOptionsMap["suppressesIncrementalRendering"] != nil && options?.suppressesIncrementalRendering != newOptions.suppressesIncrementalRendering {
configuration.suppressesIncrementalRendering = newOptions.suppressesIncrementalRendering
if newSettingsMap["suppressesIncrementalRendering"] != nil && settings?.suppressesIncrementalRendering != newSettings.suppressesIncrementalRendering {
configuration.suppressesIncrementalRendering = newSettings.suppressesIncrementalRendering
}
if newOptionsMap["allowsBackForwardNavigationGestures"] != nil && options?.allowsBackForwardNavigationGestures != newOptions.allowsBackForwardNavigationGestures {
allowsBackForwardNavigationGestures = newOptions.allowsBackForwardNavigationGestures
if newSettingsMap["allowsBackForwardNavigationGestures"] != nil && settings?.allowsBackForwardNavigationGestures != newSettings.allowsBackForwardNavigationGestures {
allowsBackForwardNavigationGestures = newSettings.allowsBackForwardNavigationGestures
}
if newOptionsMap["javaScriptCanOpenWindowsAutomatically"] != nil && options?.javaScriptCanOpenWindowsAutomatically != newOptions.javaScriptCanOpenWindowsAutomatically {
configuration.preferences.javaScriptCanOpenWindowsAutomatically = newOptions.javaScriptCanOpenWindowsAutomatically
if newSettingsMap["javaScriptCanOpenWindowsAutomatically"] != nil && settings?.javaScriptCanOpenWindowsAutomatically != newSettings.javaScriptCanOpenWindowsAutomatically {
configuration.preferences.javaScriptCanOpenWindowsAutomatically = newSettings.javaScriptCanOpenWindowsAutomatically
}
if newOptionsMap["minimumFontSize"] != nil && options?.minimumFontSize != newOptions.minimumFontSize {
configuration.preferences.minimumFontSize = CGFloat(newOptions.minimumFontSize)
if newSettingsMap["minimumFontSize"] != nil && settings?.minimumFontSize != newSettings.minimumFontSize {
configuration.preferences.minimumFontSize = CGFloat(newSettings.minimumFontSize)
}
if newOptionsMap["selectionGranularity"] != nil && options?.selectionGranularity != newOptions.selectionGranularity {
configuration.selectionGranularity = WKSelectionGranularity.init(rawValue: newOptions.selectionGranularity)!
if newSettingsMap["selectionGranularity"] != nil && settings?.selectionGranularity != newSettings.selectionGranularity {
configuration.selectionGranularity = WKSelectionGranularity.init(rawValue: newSettings.selectionGranularity)!
}
if #available(iOS 10.0, *) {
if newOptionsMap["ignoresViewportScaleLimits"] != nil && options?.ignoresViewportScaleLimits != newOptions.ignoresViewportScaleLimits {
configuration.ignoresViewportScaleLimits = newOptions.ignoresViewportScaleLimits
if newSettingsMap["ignoresViewportScaleLimits"] != nil && settings?.ignoresViewportScaleLimits != newSettings.ignoresViewportScaleLimits {
configuration.ignoresViewportScaleLimits = newSettings.ignoresViewportScaleLimits
}
if newOptionsMap["dataDetectorTypes"] != nil && options?.dataDetectorTypes != newOptions.dataDetectorTypes {
if newSettingsMap["dataDetectorTypes"] != nil && settings?.dataDetectorTypes != newSettings.dataDetectorTypes {
var dataDetectorTypes = WKDataDetectorTypes.init(rawValue: 0)
for type in newOptions.dataDetectorTypes {
for type in newSettings.dataDetectorTypes {
let dataDetectorType = Util.getDataDetectorType(type: type)
dataDetectorTypes = WKDataDetectorTypes(rawValue: dataDetectorTypes.rawValue | dataDetectorType.rawValue)
}
@ -973,112 +973,112 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
if #available(iOS 13.0, *) {
if newOptionsMap["isFraudulentWebsiteWarningEnabled"] != nil && options?.isFraudulentWebsiteWarningEnabled != newOptions.isFraudulentWebsiteWarningEnabled {
configuration.preferences.isFraudulentWebsiteWarningEnabled = newOptions.isFraudulentWebsiteWarningEnabled
if newSettingsMap["isFraudulentWebsiteWarningEnabled"] != nil && settings?.isFraudulentWebsiteWarningEnabled != newSettings.isFraudulentWebsiteWarningEnabled {
configuration.preferences.isFraudulentWebsiteWarningEnabled = newSettings.isFraudulentWebsiteWarningEnabled
}
if newOptionsMap["preferredContentMode"] != nil && options?.preferredContentMode != newOptions.preferredContentMode {
configuration.defaultWebpagePreferences.preferredContentMode = WKWebpagePreferences.ContentMode(rawValue: newOptions.preferredContentMode)!
if newSettingsMap["preferredContentMode"] != nil && settings?.preferredContentMode != newSettings.preferredContentMode {
configuration.defaultWebpagePreferences.preferredContentMode = WKWebpagePreferences.ContentMode(rawValue: newSettings.preferredContentMode)!
}
if newOptionsMap["automaticallyAdjustsScrollIndicatorInsets"] != nil && options?.automaticallyAdjustsScrollIndicatorInsets != newOptions.automaticallyAdjustsScrollIndicatorInsets {
scrollView.automaticallyAdjustsScrollIndicatorInsets = newOptions.automaticallyAdjustsScrollIndicatorInsets
if newSettingsMap["automaticallyAdjustsScrollIndicatorInsets"] != nil && settings?.automaticallyAdjustsScrollIndicatorInsets != newSettings.automaticallyAdjustsScrollIndicatorInsets {
scrollView.automaticallyAdjustsScrollIndicatorInsets = newSettings.automaticallyAdjustsScrollIndicatorInsets
}
}
if newOptionsMap["disableVerticalScroll"] != nil && options?.disableVerticalScroll != newOptions.disableVerticalScroll {
scrollView.showsVerticalScrollIndicator = !newOptions.disableVerticalScroll
if newSettingsMap["disableVerticalScroll"] != nil && settings?.disableVerticalScroll != newSettings.disableVerticalScroll {
scrollView.showsVerticalScrollIndicator = !newSettings.disableVerticalScroll
}
if newOptionsMap["disableHorizontalScroll"] != nil && options?.disableHorizontalScroll != newOptions.disableHorizontalScroll {
scrollView.showsHorizontalScrollIndicator = !newOptions.disableHorizontalScroll
if newSettingsMap["disableHorizontalScroll"] != nil && settings?.disableHorizontalScroll != newSettings.disableHorizontalScroll {
scrollView.showsHorizontalScrollIndicator = !newSettings.disableHorizontalScroll
}
if newOptionsMap["verticalScrollBarEnabled"] != nil && options?.verticalScrollBarEnabled != newOptions.verticalScrollBarEnabled {
scrollView.showsVerticalScrollIndicator = newOptions.verticalScrollBarEnabled
if newSettingsMap["verticalScrollBarEnabled"] != nil && settings?.verticalScrollBarEnabled != newSettings.verticalScrollBarEnabled {
scrollView.showsVerticalScrollIndicator = newSettings.verticalScrollBarEnabled
}
if newOptionsMap["horizontalScrollBarEnabled"] != nil && options?.horizontalScrollBarEnabled != newOptions.horizontalScrollBarEnabled {
scrollView.showsHorizontalScrollIndicator = newOptions.horizontalScrollBarEnabled
if newSettingsMap["horizontalScrollBarEnabled"] != nil && settings?.horizontalScrollBarEnabled != newSettings.horizontalScrollBarEnabled {
scrollView.showsHorizontalScrollIndicator = newSettings.horizontalScrollBarEnabled
}
if newOptionsMap["isDirectionalLockEnabled"] != nil && options?.isDirectionalLockEnabled != newOptions.isDirectionalLockEnabled {
scrollView.isDirectionalLockEnabled = newOptions.isDirectionalLockEnabled
if newSettingsMap["isDirectionalLockEnabled"] != nil && settings?.isDirectionalLockEnabled != newSettings.isDirectionalLockEnabled {
scrollView.isDirectionalLockEnabled = newSettings.isDirectionalLockEnabled
}
if newOptionsMap["decelerationRate"] != nil && options?.decelerationRate != newOptions.decelerationRate {
scrollView.decelerationRate = Util.getDecelerationRate(type: newOptions.decelerationRate)
if newSettingsMap["decelerationRate"] != nil && settings?.decelerationRate != newSettings.decelerationRate {
scrollView.decelerationRate = Util.getDecelerationRate(type: newSettings.decelerationRate)
}
if newOptionsMap["alwaysBounceVertical"] != nil && options?.alwaysBounceVertical != newOptions.alwaysBounceVertical {
scrollView.alwaysBounceVertical = newOptions.alwaysBounceVertical
if newSettingsMap["alwaysBounceVertical"] != nil && settings?.alwaysBounceVertical != newSettings.alwaysBounceVertical {
scrollView.alwaysBounceVertical = newSettings.alwaysBounceVertical
}
if newOptionsMap["alwaysBounceHorizontal"] != nil && options?.alwaysBounceHorizontal != newOptions.alwaysBounceHorizontal {
scrollView.alwaysBounceHorizontal = newOptions.alwaysBounceHorizontal
if newSettingsMap["alwaysBounceHorizontal"] != nil && settings?.alwaysBounceHorizontal != newSettings.alwaysBounceHorizontal {
scrollView.alwaysBounceHorizontal = newSettings.alwaysBounceHorizontal
}
if newOptionsMap["scrollsToTop"] != nil && options?.scrollsToTop != newOptions.scrollsToTop {
scrollView.scrollsToTop = newOptions.scrollsToTop
if newSettingsMap["scrollsToTop"] != nil && settings?.scrollsToTop != newSettings.scrollsToTop {
scrollView.scrollsToTop = newSettings.scrollsToTop
}
if newOptionsMap["isPagingEnabled"] != nil && options?.isPagingEnabled != newOptions.isPagingEnabled {
scrollView.scrollsToTop = newOptions.isPagingEnabled
if newSettingsMap["isPagingEnabled"] != nil && settings?.isPagingEnabled != newSettings.isPagingEnabled {
scrollView.scrollsToTop = newSettings.isPagingEnabled
}
if newOptionsMap["maximumZoomScale"] != nil && options?.maximumZoomScale != newOptions.maximumZoomScale {
scrollView.maximumZoomScale = CGFloat(newOptions.maximumZoomScale)
if newSettingsMap["maximumZoomScale"] != nil && settings?.maximumZoomScale != newSettings.maximumZoomScale {
scrollView.maximumZoomScale = CGFloat(newSettings.maximumZoomScale)
}
if newOptionsMap["minimumZoomScale"] != nil && options?.minimumZoomScale != newOptions.minimumZoomScale {
scrollView.minimumZoomScale = CGFloat(newOptions.minimumZoomScale)
if newSettingsMap["minimumZoomScale"] != nil && settings?.minimumZoomScale != newSettings.minimumZoomScale {
scrollView.minimumZoomScale = CGFloat(newSettings.minimumZoomScale)
}
if #available(iOS 9.0, *) {
if newOptionsMap["allowsLinkPreview"] != nil && options?.allowsLinkPreview != newOptions.allowsLinkPreview {
allowsLinkPreview = newOptions.allowsLinkPreview
if newSettingsMap["allowsLinkPreview"] != nil && settings?.allowsLinkPreview != newSettings.allowsLinkPreview {
allowsLinkPreview = newSettings.allowsLinkPreview
}
if newOptionsMap["allowsAirPlayForMediaPlayback"] != nil && options?.allowsAirPlayForMediaPlayback != newOptions.allowsAirPlayForMediaPlayback {
configuration.allowsAirPlayForMediaPlayback = newOptions.allowsAirPlayForMediaPlayback
if newSettingsMap["allowsAirPlayForMediaPlayback"] != nil && settings?.allowsAirPlayForMediaPlayback != newSettings.allowsAirPlayForMediaPlayback {
configuration.allowsAirPlayForMediaPlayback = newSettings.allowsAirPlayForMediaPlayback
}
if newOptionsMap["allowsPictureInPictureMediaPlayback"] != nil && options?.allowsPictureInPictureMediaPlayback != newOptions.allowsPictureInPictureMediaPlayback {
configuration.allowsPictureInPictureMediaPlayback = newOptions.allowsPictureInPictureMediaPlayback
if newSettingsMap["allowsPictureInPictureMediaPlayback"] != nil && settings?.allowsPictureInPictureMediaPlayback != newSettings.allowsPictureInPictureMediaPlayback {
configuration.allowsPictureInPictureMediaPlayback = newSettings.allowsPictureInPictureMediaPlayback
}
if newOptionsMap["applicationNameForUserAgent"] != nil && options?.applicationNameForUserAgent != newOptions.applicationNameForUserAgent && newOptions.applicationNameForUserAgent != "" {
configuration.applicationNameForUserAgent = newOptions.applicationNameForUserAgent
if newSettingsMap["applicationNameForUserAgent"] != nil && settings?.applicationNameForUserAgent != newSettings.applicationNameForUserAgent && newSettings.applicationNameForUserAgent != "" {
configuration.applicationNameForUserAgent = newSettings.applicationNameForUserAgent
}
if newOptionsMap["userAgent"] != nil && options?.userAgent != newOptions.userAgent && newOptions.userAgent != "" {
customUserAgent = newOptions.userAgent
if newSettingsMap["userAgent"] != nil && settings?.userAgent != newSettings.userAgent && newSettings.userAgent != "" {
customUserAgent = newSettings.userAgent
}
}
if newOptionsMap["allowUniversalAccessFromFileURLs"] != nil && options?.allowUniversalAccessFromFileURLs != newOptions.allowUniversalAccessFromFileURLs {
configuration.setValue(newOptions.allowUniversalAccessFromFileURLs, forKey: "allowUniversalAccessFromFileURLs")
if newSettingsMap["allowUniversalAccessFromFileURLs"] != nil && settings?.allowUniversalAccessFromFileURLs != newSettings.allowUniversalAccessFromFileURLs {
configuration.setValue(newSettings.allowUniversalAccessFromFileURLs, forKey: "allowUniversalAccessFromFileURLs")
}
if newOptionsMap["allowFileAccessFromFileURLs"] != nil && options?.allowFileAccessFromFileURLs != newOptions.allowFileAccessFromFileURLs {
configuration.preferences.setValue(newOptions.allowFileAccessFromFileURLs, forKey: "allowFileAccessFromFileURLs")
if newSettingsMap["allowFileAccessFromFileURLs"] != nil && settings?.allowFileAccessFromFileURLs != newSettings.allowFileAccessFromFileURLs {
configuration.preferences.setValue(newSettings.allowFileAccessFromFileURLs, forKey: "allowFileAccessFromFileURLs")
}
if newOptionsMap["clearCache"] != nil && newOptions.clearCache {
if newSettingsMap["clearCache"] != nil && newSettings.clearCache {
clearCache()
}
if newOptionsMap["javaScriptEnabled"] != nil && options?.javaScriptEnabled != newOptions.javaScriptEnabled {
configuration.preferences.javaScriptEnabled = newOptions.javaScriptEnabled
if newSettingsMap["javaScriptEnabled"] != nil && settings?.javaScriptEnabled != newSettings.javaScriptEnabled {
configuration.preferences.javaScriptEnabled = newSettings.javaScriptEnabled
}
if #available(iOS 14.0, *) {
if options?.mediaType != newOptions.mediaType {
mediaType = newOptions.mediaType
if settings?.mediaType != newSettings.mediaType {
mediaType = newSettings.mediaType
}
if newOptionsMap["pageZoom"] != nil && options?.pageZoom != newOptions.pageZoom {
pageZoom = CGFloat(newOptions.pageZoom)
if newSettingsMap["pageZoom"] != nil && settings?.pageZoom != newSettings.pageZoom {
pageZoom = CGFloat(newSettings.pageZoom)
}
if newOptionsMap["limitsNavigationsToAppBoundDomains"] != nil && options?.limitsNavigationsToAppBoundDomains != newOptions.limitsNavigationsToAppBoundDomains {
configuration.limitsNavigationsToAppBoundDomains = newOptions.limitsNavigationsToAppBoundDomains
if newSettingsMap["limitsNavigationsToAppBoundDomains"] != nil && settings?.limitsNavigationsToAppBoundDomains != newSettings.limitsNavigationsToAppBoundDomains {
configuration.limitsNavigationsToAppBoundDomains = newSettings.limitsNavigationsToAppBoundDomains
}
if newOptionsMap["javaScriptEnabled"] != nil && options?.javaScriptEnabled != newOptions.javaScriptEnabled {
configuration.defaultWebpagePreferences.allowsContentJavaScript = newOptions.javaScriptEnabled
if newSettingsMap["javaScriptEnabled"] != nil && settings?.javaScriptEnabled != newSettings.javaScriptEnabled {
configuration.defaultWebpagePreferences.allowsContentJavaScript = newSettings.javaScriptEnabled
}
}
if #available(iOS 11.0, *), newOptionsMap["contentBlockers"] != nil {
if #available(iOS 11.0, *), newSettingsMap["contentBlockers"] != nil {
configuration.userContentController.removeAllContentRuleLists()
let contentBlockers = newOptions.contentBlockers
let contentBlockers = newSettings.contentBlockers
if contentBlockers.count > 0 {
do {
let jsonData = try JSONSerialization.data(withJSONObject: contentBlockers, options: [])
@ -1098,16 +1098,16 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
}
scrollView.isScrollEnabled = !(newOptions.disableVerticalScroll && newOptions.disableHorizontalScroll)
scrollView.isScrollEnabled = !(newSettings.disableVerticalScroll && newSettings.disableHorizontalScroll)
self.options = newOptions
self.settings = newSettings
}
func getOptions() -> [String: Any?]? {
if (self.options == nil) {
func getSettings() -> [String: Any?]? {
if (self.settings == nil) {
return nil
}
return self.options!.getRealOptions(obj: self)
return self.settings!.getRealSettings(obj: self)
}
public func enablePluginScriptAtRuntime(flagVariable: String, enable: Bool, pluginScript: PluginScript) {
@ -1224,7 +1224,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
public override func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((Any?, Error?) -> Void)? = nil) {
if let applePayAPIEnabled = options?.applePayAPIEnabled, applePayAPIEnabled {
if let applePayAPIEnabled = settings?.applePayAPIEnabled, applePayAPIEnabled {
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
@ -1235,7 +1235,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
@available(iOS 14.0, *)
public func evaluateJavaScript(_ javaScript: String, frame: WKFrameInfo? = nil, contentWorld: WKContentWorld, completionHandler: ((Result<Any, Error>) -> Void)? = nil) {
if let applePayAPIEnabled = options?.applePayAPIEnabled, applePayAPIEnabled {
if let applePayAPIEnabled = settings?.applePayAPIEnabled, applePayAPIEnabled {
return
}
super.evaluateJavaScript(javaScript, in: frame, in: contentWorld, completionHandler: completionHandler)
@ -1252,7 +1252,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
@available(iOS 14.0, *)
public func callAsyncJavaScript(_ functionBody: String, arguments: [String : Any] = [:], frame: WKFrameInfo? = nil, contentWorld: WKContentWorld, completionHandler: ((Result<Any, Error>) -> Void)? = nil) {
if let applePayAPIEnabled = options?.applePayAPIEnabled, applePayAPIEnabled {
if let applePayAPIEnabled = settings?.applePayAPIEnabled, applePayAPIEnabled {
return
}
super.callAsyncJavaScript(functionBody, arguments: arguments, in: frame, in: contentWorld, completionHandler: completionHandler)
@ -1291,7 +1291,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
@available(iOS 10.3, *)
public func callAsyncJavaScript(functionBody: String, arguments: [String:Any], completionHandler: ((Any?) -> Void)? = nil) {
if let applePayAPIEnabled = options?.applePayAPIEnabled, applePayAPIEnabled {
if let applePayAPIEnabled = settings?.applePayAPIEnabled, applePayAPIEnabled {
completionHandler?(nil)
}
@ -1468,7 +1468,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
if navigationAction.request.url != nil {
if let useShouldOverrideUrlLoading = options?.useShouldOverrideUrlLoading, useShouldOverrideUrlLoading {
if let useShouldOverrideUrlLoading = settings?.useShouldOverrideUrlLoading, useShouldOverrideUrlLoading {
shouldOverrideUrlLoading(navigationAction: navigationAction, result: { (result) -> Void in
if result is FlutterError {
print((result as! FlutterError).message ?? "")
@ -1509,7 +1509,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
}
let useOnNavigationResponse = options?.useOnNavigationResponse
let useOnNavigationResponse = settings?.useOnNavigationResponse
if useOnNavigationResponse != nil, useOnNavigationResponse! {
onNavigationResponse(navigationResponse: navigationResponse, result: { (result) -> Void in
@ -1542,7 +1542,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
})
}
if let useOnDownloadStart = options?.useOnDownloadStart, useOnDownloadStart {
if let useOnDownloadStart = settings?.useOnDownloadStart, useOnDownloadStart {
let mimeType = navigationResponse.response.mimeType
if let url = navigationResponse.response.url, navigationResponse.isForMainFrame {
if url.scheme != "file", mimeType != nil, !mimeType!.starts(with: "text/") {
@ -2064,8 +2064,8 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
/// an observer that observes the scrollView.contentOffset property.
/// This way, we don't need to call setNeedsLayout() and all works fine.
public func onScrollChanged(startedByUser: Bool, oldContentOffset: CGPoint?) {
let disableVerticalScroll = options?.disableVerticalScroll ?? false
let disableHorizontalScroll = options?.disableHorizontalScroll ?? false
let disableVerticalScroll = settings?.disableVerticalScroll ?? false
let disableHorizontalScroll = settings?.disableHorizontalScroll ?? false
if startedByUser {
if disableVerticalScroll && disableHorizontalScroll {
scrollView.contentOffset = CGPoint(x: lastScrollX, y: lastScrollY);
@ -2130,7 +2130,8 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
var arguments: [String: Any?] = navigationAction.toMap()
arguments["windowId"] = windowId
arguments["iosWindowFeatures"] = windowFeatures.toMap()
arguments["isDialog"] = nil
arguments["windowFeatures"] = windowFeatures.toMap()
channel?.invokeMethod("onCreateWindow", arguments: arguments, result: { (result) -> Void in
if result is FlutterError {
@ -2414,7 +2415,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
let arguments: [String: Any?] = [
"url": frame.request.url?.absoluteString,
"message": message,
"iosIsMainFrame": frame.isMainFrame
"isMainFrame": frame.isMainFrame
]
channel?.invokeMethod("onJsAlert", arguments: arguments, result: result)
}
@ -2423,7 +2424,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
let arguments: [String: Any?] = [
"url": frame.request.url?.absoluteString,
"message": message,
"iosIsMainFrame": frame.isMainFrame
"isMainFrame": frame.isMainFrame
]
channel?.invokeMethod("onJsConfirm", arguments: arguments, result: result)
}
@ -2433,7 +2434,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
"url": frame.request.url?.absoluteString,
"message": message,
"defaultValue": defaultValue as Any,
"iosIsMainFrame": frame.isMainFrame
"isMainFrame": frame.isMainFrame
]
channel?.invokeMethod("onJsPrompt", arguments: arguments, result: result)
}
@ -2957,6 +2958,6 @@ if(window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)] != null) {
// https://stackoverflow.com/a/58001395/4637638
public override var inputAccessoryView: UIView? {
return options?.disableInputAccessoryView ?? false ? nil : super.inputAccessoryView
return settings?.disableInputAccessoryView ?? false ? nil : super.inputAccessoryView
}
}

View File

@ -1,5 +1,5 @@
//
// InAppWebViewOptions.swift
// InAppWebViewSettings.swift
// flutter_inappwebview
//
// Created by Lorenzo on 21/10/18.

View File

@ -153,25 +153,25 @@ public class InAppWebViewMethodHandler: FlutterMethodCallDelegate {
result(nil)
}
break
case "setOptions":
case "setSettings":
if let iabController = webView?.inAppBrowserDelegate as? InAppBrowserWebViewController {
let inAppBrowserOptions = InAppBrowserOptions()
let inAppBrowserOptionsMap = arguments!["options"] as! [String: Any]
let _ = inAppBrowserOptions.parse(options: inAppBrowserOptionsMap)
iabController.setOptions(newOptions: inAppBrowserOptions, newOptionsMap: inAppBrowserOptionsMap)
let inAppBrowserSettings = InAppBrowserSettings()
let inAppBrowserSettingsMap = arguments!["settings"] as! [String: Any]
let _ = inAppBrowserSettings.parse(settings: inAppBrowserSettingsMap)
iabController.setSettings(newSettings: inAppBrowserSettings, newSettingsMap: inAppBrowserSettingsMap)
} else {
let inAppWebViewOptions = InAppWebViewOptions()
let inAppWebViewOptionsMap = arguments!["options"] as! [String: Any]
let _ = inAppWebViewOptions.parse(options: inAppWebViewOptionsMap)
webView?.setOptions(newOptions: inAppWebViewOptions, newOptionsMap: inAppWebViewOptionsMap)
let inAppWebViewSettings = InAppWebViewSettings()
let inAppWebViewSettingsMap = arguments!["settings"] as! [String: Any]
let _ = inAppWebViewSettings.parse(settings: inAppWebViewSettingsMap)
webView?.setSettings(newSettings: inAppWebViewSettings, newSettingsMap: inAppWebViewSettingsMap)
}
result(true)
break
case "getOptions":
case "getSettings":
if let iabController = webView?.inAppBrowserDelegate as? InAppBrowserWebViewController {
result(iabController.getOptions())
result(iabController.getSettings())
} else {
result(webView?.getOptions())
result(webView?.getSettings())
}
break
case "close":
@ -441,7 +441,7 @@ public class InAppWebViewMethodHandler: FlutterMethodCallDelegate {
break
case "createPdf":
if let webView = webView, #available(iOS 14.0, *) {
let configuration = arguments!["iosWKPdfConfiguration"] as? [String: Any?]
let configuration = arguments!["pdfConfiguration"] as? [String: Any?]
webView.createPdf(configuration: configuration, completionHandler: { (pdf) -> Void in
result(pdf)
})

View File

@ -11,11 +11,11 @@ import Flutter
public class PullToRefreshControl : UIRefreshControl, FlutterPlugin {
var channel: FlutterMethodChannel?
var options: PullToRefreshOptions?
var options: PullToRefreshSettings?
var shouldCallOnRefresh = false
var delegate: PullToRefreshDelegate?
public init(channel: FlutterMethodChannel?, options: PullToRefreshOptions?) {
public init(channel: FlutterMethodChannel?, options: PullToRefreshSettings?) {
super.init()
self.channel = channel
self.options = options

View File

@ -18,16 +18,16 @@ public class PullToRefreshSettings : IWebViewSettings<PullToRefreshControl> {
super.init()
}
override func parse(options: [String: Any?]) -> PullToRefreshSettings {
let _ = super.parse(options: options)
if let attributedTitle = options["attributedTitle"] as? [String: Any?] {
override func parse(settings: [String: Any?]) -> PullToRefreshSettings {
let _ = super.parse(settings: settings)
if let attributedTitle = settings["attributedTitle"] as? [String: Any?] {
self.attributedTitle = attributedTitle
}
return self
}
override func getRealSettings(obj: PullToRefreshControl?) -> [String: Any?] {
let realOptions: [String: Any?] = toMap()
return realOptions
let realSettings: [String: Any?] = toMap()
return realSettings
}
}

View File

@ -9,7 +9,7 @@ import Foundation
@available(iOS 9.0, *)
@objcMembers
public class SafariBrowserOptions: Options<SafariViewController> {
public class SafariBrowserOptions: IWebViewSettings<SafariViewController> {
var entersReaderIfAvailable = false
var barCollapsingEnabled = false
@ -23,7 +23,7 @@ public class SafariBrowserOptions: Options<SafariViewController> {
super.init()
}
override func getRealOptions(obj: SafariViewController?) -> [String: Any?] {
override func getRealSettings(obj: SafariViewController?) -> [String: Any?] {
var realOptions: [String: Any?] = toMap()
if let safariViewController = obj {
if #available(iOS 11.0, *) {

View File

@ -43,7 +43,7 @@ public class SslError: NSObject {
public func toMap () -> [String:Any?] {
return [
"iosError": errorType?.rawValue,
"code": errorType?.rawValue,
"message": message
]
}

View File

@ -12,8 +12,8 @@ extension URLAuthenticationChallenge {
return [
"protectionSpace": protectionSpace.toMap(),
"previousFailureCount": previousFailureCount,
"iosFailureResponse": failureResponse?.toMap(),
"iosError": error?.localizedDescription,
"failureResponse": failureResponse?.toMap(),
"error": error?.localizedDescription,
"proposedCredential": proposedCredential?.toMap(),
]
}

View File

@ -19,8 +19,8 @@ extension URLCredential {
return [
"password": password,
"username": user,
"iosCertificates": x509Certificates,
"iosPersistence": persistence.rawValue
"certificates": x509Certificates,
"persistence": persistence.rawValue
]
}
}

View File

@ -54,11 +54,11 @@ extension URLProtectionSpace {
"port": port,
"sslCertificate": sslCertificate?.toMap(),
"sslError": sslError?.toMap(),
"iosAuthenticationMethod": authenticationMethod,
"iosDistinguishedNames": distinguishedNames,
"iosReceivesCredentialSecurely": receivesCredentialSecurely,
"iosIsProxy": isProxy(),
"iosProxyType": proxyType
"authenticationMethod": authenticationMethod,
"distinguishedNames": distinguishedNames,
"receivesCredentialSecurely": receivesCredentialSecurely,
"isProxy": isProxy(),
"proxyType": proxyType
]
}
}

View File

@ -23,31 +23,31 @@ extension URLRequest {
setValue(value, forHTTPHeaderField: key)
}
}
if let iosAllowsCellularAccess = fromPluginMap["iosAllowsCellularAccess"] as? Bool {
if let iosAllowsCellularAccess = fromPluginMap["allowsCellularAccess"] as? Bool {
allowsCellularAccess = iosAllowsCellularAccess
}
if #available(iOS 13.0, *), let iosAllowsConstrainedNetworkAccess = fromPluginMap["iosAllowsConstrainedNetworkAccess"] as? Bool {
if #available(iOS 13.0, *), let iosAllowsConstrainedNetworkAccess = fromPluginMap["allowsConstrainedNetworkAccess"] as? Bool {
allowsConstrainedNetworkAccess = iosAllowsConstrainedNetworkAccess
}
if #available(iOS 13.0, *), let iosAllowsExpensiveNetworkAccess = fromPluginMap["iosAllowsExpensiveNetworkAccess"] as? Bool {
if #available(iOS 13.0, *), let iosAllowsExpensiveNetworkAccess = fromPluginMap["allowsExpensiveNetworkAccess"] as? Bool {
allowsExpensiveNetworkAccess = iosAllowsExpensiveNetworkAccess
}
if let iosCachePolicy = fromPluginMap["iosCachePolicy"] as? Int {
if let iosCachePolicy = fromPluginMap["cachePolicy"] as? Int {
cachePolicy = CachePolicy.init(rawValue: UInt(iosCachePolicy)) ?? .useProtocolCachePolicy
}
if let iosHttpShouldHandleCookies = fromPluginMap["iosHttpShouldHandleCookies"] as? Bool {
if let iosHttpShouldHandleCookies = fromPluginMap["httpShouldHandleCookies"] as? Bool {
httpShouldHandleCookies = iosHttpShouldHandleCookies
}
if let iosHttpShouldUsePipelining = fromPluginMap["iosHttpShouldUsePipelining"] as? Bool {
if let iosHttpShouldUsePipelining = fromPluginMap["httpShouldUsePipelining"] as? Bool {
httpShouldUsePipelining = iosHttpShouldUsePipelining
}
if let iosNetworkServiceType = fromPluginMap["iosNetworkServiceType"] as? Int {
if let iosNetworkServiceType = fromPluginMap["networkServiceType"] as? Int {
networkServiceType = NetworkServiceType.init(rawValue: UInt(iosNetworkServiceType)) ?? .default
}
if let iosTimeoutInterval = fromPluginMap["iosTimeoutInterval"] as? Double {
if let iosTimeoutInterval = fromPluginMap["timeoutInterval"] as? Double {
timeoutInterval = iosTimeoutInterval
}
if let iosMainDocumentURL = fromPluginMap["iosMainDocumentURL"] as? String {
if let iosMainDocumentURL = fromPluginMap["mainDocumentURL"] as? String {
mainDocumentURL = URL(string: iosMainDocumentURL)!
}
}
@ -64,15 +64,15 @@ extension URLRequest {
"method": httpMethod,
"headers": allHTTPHeaderFields,
"body": httpBody.map(FlutterStandardTypedData.init(bytes:)),
"iosAllowsCellularAccess": allowsCellularAccess,
"iosAllowsConstrainedNetworkAccess": iosAllowsConstrainedNetworkAccess,
"iosAllowsExpensiveNetworkAccess": iosAllowsExpensiveNetworkAccess,
"iosCachePolicy": cachePolicy.rawValue,
"iosHttpShouldHandleCookies": httpShouldHandleCookies,
"iosHttpShouldUsePipelining": httpShouldUsePipelining,
"iosNetworkServiceType": networkServiceType.rawValue,
"iosTimeoutInterval": timeoutInterval,
"iosMainDocumentURL": mainDocumentURL?.absoluteString
"allowsCellularAccess": allowsCellularAccess,
"allowsConstrainedNetworkAccess": iosAllowsConstrainedNetworkAccess,
"allowsExpensiveNetworkAccess": iosAllowsExpensiveNetworkAccess,
"cachePolicy": cachePolicy.rawValue,
"httpShouldHandleCookies": httpShouldHandleCookies,
"httpShouldUsePipelining": httpShouldUsePipelining,
"networkServiceType": networkServiceType.rawValue,
"timeoutInterval": timeoutInterval,
"mainDocumentURL": mainDocumentURL?.absoluteString
]
}
}

View File

@ -47,7 +47,7 @@ public class UserScript : WKUserScript {
groupName: map["groupName"] as? String,
source: map["source"] as! String,
injectionTime: WKUserScriptInjectionTime.init(rawValue: map["injectionTime"] as! Int) ?? .atDocumentStart,
forMainFrameOnly: map["iosForMainFrameOnly"] as! Bool,
forMainFrameOnly: map["forMainFrameOnly"] as! Bool,
in: contentWorld
)
}
@ -55,7 +55,7 @@ public class UserScript : WKUserScript {
groupName: map["groupName"] as? String,
source: map["source"] as! String,
injectionTime: WKUserScriptInjectionTime.init(rawValue: map["injectionTime"] as! Int) ?? .atDocumentStart,
forMainFrameOnly: map["iosForMainFrameOnly"] as! Bool
forMainFrameOnly: map["forMainFrameOnly"] as! Bool
)
}
}

View File

@ -13,9 +13,11 @@ extension WKNavigationAction {
return [
"request": request.toMap(),
"isForMainFrame": targetFrame?.isMainFrame ?? false,
"iosWKNavigationType": navigationType.rawValue,
"iosSourceFrame": sourceFrame.toMap(),
"iosTargetFrame": targetFrame?.toMap()
"hasGesture": nil,
"isRedirect": nil,
"navigationType": navigationType.rawValue,
"sourceFrame": sourceFrame.toMap(),
"targetFrame": targetFrame?.toMap()
]
}
}

View File

@ -152,7 +152,7 @@ class AndroidWebViewFeature {
"SAFE_BROWSING_RESPONSE_SHOW_INTERSTITIAL");
///Use [SAFE_BROWSING_ALLOWLIST] instead.
@Deprecated('Use `SAFE_BROWSING_ALLOWLIST` instead')
@Deprecated('Use SAFE_BROWSING_ALLOWLIST instead')
static const SAFE_BROWSING_WHITELIST =
const AndroidWebViewFeature._internal("SAFE_BROWSING_WHITELIST");

View File

@ -12,7 +12,7 @@ import '../../in_app_webview/android/in_app_webview_options.dart';
class AndroidChromeCustomTabsOptions
implements ChromeSafariBrowserOptions, AndroidOptions {
///Use [shareState] instead.
@Deprecated('Use `shareState` instead')
@Deprecated('Use shareState instead')
bool? addDefaultShareMenuItem;
///The share state that should be applied to the custom tab. The default value is [CustomTabsShareState.SHARE_STATE_DEFAULT].
@ -73,7 +73,7 @@ class AndroidChromeCustomTabsOptions
TrustedWebActivityScreenOrientation screenOrientation;
AndroidChromeCustomTabsOptions(
{@Deprecated('Use `shareState` instead') this.addDefaultShareMenuItem,
{@Deprecated('Use shareState instead') this.addDefaultShareMenuItem,
this.shareState = CustomTabsShareState.SHARE_STATE_DEFAULT,
this.showTitle = true,
this.toolbarBackgroundColor,

View File

@ -1,11 +1,10 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'in_app_webview/in_app_webview_controller.dart';
import 'in_app_webview/in_app_webview_options.dart';
import 'in_app_webview/in_app_webview_settings.dart';
import 'in_app_webview/headless_in_app_webview.dart';
import 'platform_util.dart';
@ -15,7 +14,7 @@ import 'types.dart';
///On Android, it is implemented using [CookieManager](https://developer.android.com/reference/android/webkit/CookieManager).
///On iOS, it is implemented using [WKHTTPCookieStore](https://developer.apple.com/documentation/webkit/wkhttpcookiestore).
///
///**NOTE for iOS below 11.0 (LIMITED SUPPORT!)**: in this case, almost all of the methods ([CookieManager.deleteAllCookies] and [IOSCookieManager.getAllCookies] are not supported!)
///**NOTE for iOS below 11.0 (LIMITED SUPPORT!)**: in this case, almost all of the methods ([CookieManager.deleteAllCookies] and [CookieManager.getAllCookies] are not supported!)
///has been implemented using JavaScript because there is no other way to work with them on iOS below 11.0.
///See https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies for JavaScript restrictions.
class CookieManager {
@ -24,6 +23,8 @@ class CookieManager {
'com.pichillilorenzo/flutter_inappwebview_cookiemanager');
///Contains only iOS-specific methods of [CookieManager].
///Use [CookieManager] instead.
@Deprecated("Use CookieManager instead")
late IOSCookieManager ios;
///Gets the [CookieManager] shared instance.
@ -34,6 +35,7 @@ class CookieManager {
static CookieManager _init() {
_channel.setMethodCallHandler(_handleMethod);
_instance = CookieManager();
// ignore: deprecated_member_use_from_same_package
_instance!.ios = IOSCookieManager.instance();
return _instance!;
}
@ -51,6 +53,10 @@ class CookieManager {
///
///**NOTE for iOS below 11.0**: If [iosBelow11WebViewController] is `null` or JavaScript is disabled for it, it will try to use a [HeadlessInAppWebView]
///to set the cookie (session-only cookie won't work! In that case, you should set also [expiresDate] or [maxAge]).
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - CookieManager.setCookie](https://developer.android.com/reference/android/webkit/CookieManager#setCookie(java.lang.String,%20java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.Boolean%3E)))
///- iOS ([Official API - WKHTTPCookieStore.setCookie](https://developer.apple.com/documentation/webkit/wkhttpcookiestore/2882007-setcookie))
Future<void> setCookie(
{required Uri url,
required String name,
@ -131,8 +137,8 @@ class CookieManager {
cookieValue += ";";
if (webViewController != null) {
InAppWebViewGroupOptions? options = await webViewController.getOptions();
if (options != null && options.crossPlatform.javaScriptEnabled) {
InAppWebViewSettings? settings = await webViewController.getSettings();
if (settings != null && settings.javaScriptEnabled) {
await webViewController.evaluateJavascript(
source: 'document.cookie="$cookieValue"');
return;
@ -162,6 +168,10 @@ class CookieManager {
///**NOTE for iOS below 11.0**: All the cookies returned this way will have all the properties to `null` except for [Cookie.name] and [Cookie.value].
///If [iosBelow11WebViewController] is `null` or JavaScript is disabled for it, it will try to use a [HeadlessInAppWebView]
///to get the cookies (session-only cookies and cookies with `isHttpOnly` enabled won't be found!).
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - CookieManager.getCookie](https://developer.android.com/reference/android/webkit/CookieManager#getCookie(java.lang.String)))
///- iOS ([Official API - WKHTTPCookieStore.getAllCookies](https://developer.apple.com/documentation/webkit/wkhttpcookiestore/2882005-getallcookies))
Future<List<Cookie>> getCookies(
{required Uri url,
InAppWebViewController? iosBelow11WebViewController}) async {
@ -206,8 +216,8 @@ class CookieManager {
List<Cookie> cookies = [];
if (webViewController != null) {
InAppWebViewGroupOptions? options = await webViewController.getOptions();
if (options != null && options.crossPlatform.javaScriptEnabled) {
InAppWebViewSettings? settings = await webViewController.getSettings();
if (settings != null && settings.javaScriptEnabled) {
List<String> documentCookies = (await webViewController
.evaluateJavascript(source: 'document.cookie') as String)
.split(';')
@ -259,6 +269,10 @@ class CookieManager {
///**NOTE for iOS below 11.0**: All the cookies returned this way will have all the properties to `null` except for [Cookie.name] and [Cookie.value].
///If [iosBelow11WebViewController] is `null` or JavaScript is disabled for it, it will try to use a [HeadlessInAppWebView]
///to get the cookie (session-only cookie and cookie with `isHttpOnly` enabled won't be found!).
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
Future<Cookie?> getCookie(
{required Uri url,
required String name,
@ -311,6 +325,10 @@ class CookieManager {
///
///**NOTE for iOS below 11.0**: If [iosBelow11WebViewController] is `null` or JavaScript is disabled for it, it will try to use a [HeadlessInAppWebView]
///to delete the cookie (session-only cookie and cookie with `isHttpOnly` enabled won't be deleted!).
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS ([Official API - WKHTTPCookieStore.delete](https://developer.apple.com/documentation/webkit/wkhttpcookiestore/2882009-delete)
Future<void> deleteCookie(
{required Uri url,
required String name,
@ -357,6 +375,10 @@ class CookieManager {
///
///**NOTE for iOS below 11.0**: If [iosBelow11WebViewController] is `null` or JavaScript is disabled for it, it will try to use a [HeadlessInAppWebView]
///to delete the cookies (session-only cookies and cookies with `isHttpOnly` enabled won't be deleted!).
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
Future<void> deleteCookies(
{required Uri url,
String domain = "",
@ -396,11 +418,44 @@ class CookieManager {
///Removes all cookies.
///
///**NOTE for iOS**: available from iOS 11.0+.
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - CookieManager.removeAllCookies](https://developer.android.com/reference/android/webkit/CookieManager#removeAllCookies(android.webkit.ValueCallback%3Cjava.lang.Boolean%3E)))
///- iOS ([Official API - WKWebsiteDataStore.removeData](https://developer.apple.com/documentation/webkit/wkwebsitedatastore/1532938-removedata))
Future<void> deleteAllCookies() async {
Map<String, dynamic> args = <String, dynamic>{};
await _channel.invokeMethod('deleteAllCookies', args);
}
///Fetches all stored cookies.
///
///**NOTE**: available on iOS 11.0+.
///
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKHTTPCookieStore.getAllCookies](https://developer.apple.com/documentation/webkit/wkhttpcookiestore/2882005-getallcookies))
Future<List<Cookie>> getAllCookies() async {
List<Cookie> cookies = [];
Map<String, dynamic> args = <String, dynamic>{};
List<dynamic> cookieListMap =
await CookieManager._channel.invokeMethod('getAllCookies', args);
cookieListMap = cookieListMap.cast<Map<dynamic, dynamic>>();
cookieListMap.forEach((cookieMap) {
cookies.add(Cookie(
name: cookieMap["name"],
value: cookieMap["value"],
expiresDate: cookieMap["expiresDate"],
isSessionOnly: cookieMap["isSessionOnly"],
domain: cookieMap["domain"],
sameSite: HTTPCookieSameSitePolicy.fromValue(cookieMap["sameSite"]),
isSecure: cookieMap["isSecure"],
isHttpOnly: cookieMap["isHttpOnly"],
path: cookieMap["path"]));
});
return cookies;
}
String _getDomainName(Uri url) {
String domain = url.host;
return domain.startsWith("www.") ? domain.substring(4) : domain;
@ -418,6 +473,8 @@ class CookieManager {
}
///Class that contains only iOS-specific methods of [CookieManager].
///Use [CookieManager] instead.
@Deprecated("Use CookieManager instead")
class IOSCookieManager {
static IOSCookieManager? _instance;

View File

@ -3,16 +3,16 @@ import 'dart:collection';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_inappwebview/src/util.dart';
import '../context_menu.dart';
import '../pull_to_refresh/main.dart';
import '../types.dart';
import '../in_app_webview/in_app_webview_controller.dart';
import '../in_app_webview/in_app_webview_options.dart';
import '../in_app_webview/in_app_webview_settings.dart';
import 'in_app_browser_options.dart';
import '../util.dart';
import 'in_app_browser_settings.dart';
class InAppBrowserAlreadyOpenedException implements Exception {
final dynamic message;
@ -105,15 +105,19 @@ class InAppBrowser {
///[options]: Options for the [InAppBrowser].
Future<void> openUrlRequest(
{required URLRequest urlRequest,
InAppBrowserClassOptions? options}) async {
// ignore: deprecated_member_use_from_same_package
@Deprecated('Use settings instead') InAppBrowserClassOptions? options,
InAppBrowserClassSettings? settings}) async {
this.throwIfAlreadyOpened(message: 'Cannot open $urlRequest!');
assert(urlRequest.url != null && urlRequest.url.toString().isNotEmpty);
var initialSettings = settings?.toMap() ?? options?.toMap() ??
InAppBrowserClassSettings().toMap();
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('id', () => id);
args.putIfAbsent('urlRequest', () => urlRequest.toMap());
args.putIfAbsent('options',
() => options?.toMap() ?? InAppBrowserClassOptions().toMap());
args.putIfAbsent('settings', () => initialSettings);
args.putIfAbsent('contextMenu', () => contextMenu?.toMap() ?? {});
args.putIfAbsent('windowId', () => windowId);
args.putIfAbsent('implementation', () => implementation.toValue());
@ -164,15 +168,19 @@ class InAppBrowser {
///[options]: Options for the [InAppBrowser].
Future<void> openFile(
{required String assetFilePath,
InAppBrowserClassOptions? options}) async {
// ignore: deprecated_member_use_from_same_package
@Deprecated('Use settings instead') InAppBrowserClassOptions? options,
InAppBrowserClassSettings? settings}) async {
this.throwIfAlreadyOpened(message: 'Cannot open $assetFilePath!');
assert(assetFilePath.isNotEmpty);
var initialSettings = settings?.toMap() ?? options?.toMap() ??
InAppBrowserClassSettings().toMap();
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('id', () => id);
args.putIfAbsent('assetFilePath', () => assetFilePath);
args.putIfAbsent('options',
() => options?.toMap() ?? InAppBrowserClassOptions().toMap());
args.putIfAbsent('settings', () => initialSettings);
args.putIfAbsent('contextMenu', () => contextMenu?.toMap() ?? {});
args.putIfAbsent('windowId', () => windowId);
args.putIfAbsent('implementation', () => implementation.toValue());
@ -201,13 +209,18 @@ class InAppBrowser {
String encoding = "utf8",
Uri? baseUrl,
Uri? androidHistoryUrl,
InAppBrowserClassOptions? options}) async {
// ignore: deprecated_member_use_from_same_package
@Deprecated('Use settings instead') InAppBrowserClassOptions? options,
InAppBrowserClassSettings? settings}) async {
this.throwIfAlreadyOpened(message: 'Cannot open data!');
var initialSettings = settings?.toMap() ?? options?.toMap() ??
InAppBrowserClassSettings().toMap();
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('id', () => id);
args.putIfAbsent('options',
() => options?.toMap() ?? InAppBrowserClassOptions().toMap());
args.putIfAbsent('settings', () => initialSettings);
args.putIfAbsent('data', () => data);
args.putIfAbsent('mimeType', () => mimeType);
args.putIfAbsent('encoding', () => encoding);
@ -263,22 +276,24 @@ class InAppBrowser {
return await _channel.invokeMethod('isHidden', args);
}
///Sets the [InAppBrowser] options with the new [options] and evaluates them.
///Use [setSettings] instead.
@Deprecated('Use setSettings instead')
Future<void> setOptions({required InAppBrowserClassOptions options}) async {
this.throwIfNotOpened();
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('options', () => options.toMap());
await _channel.invokeMethod('setOptions', args);
args.putIfAbsent('settings', () => options.toMap());
await _channel.invokeMethod('setSettings', args);
}
///Gets the current [InAppBrowser] options. Returns `null` if it wasn't able to get them.
///Use [getSettings] instead.
@Deprecated('Use getSettings instead')
Future<InAppBrowserClassOptions?> getOptions() async {
this.throwIfNotOpened();
Map<String, dynamic> args = <String, dynamic>{};
Map<dynamic, dynamic>? options =
await _channel.invokeMethod('getOptions', args);
await _channel.invokeMethod('getSettings', args);
if (options != null) {
options = options.cast<String, dynamic>();
return InAppBrowserClassOptions.fromMap(options as Map<String, dynamic>);
@ -287,6 +302,30 @@ class InAppBrowser {
return null;
}
///Sets the [InAppBrowser] settings with the new [settings] and evaluates them.
Future<void> setSettings({required InAppBrowserClassSettings settings}) async {
this.throwIfNotOpened();
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('settings', () => settings.toMap());
await _channel.invokeMethod('setSettings', args);
}
///Gets the current [InAppBrowser] settings. Returns `null` if it wasn't able to get them.
Future<InAppBrowserClassSettings?> getSettings() async {
this.throwIfNotOpened();
Map<String, dynamic> args = <String, dynamic>{};
Map<dynamic, dynamic>? settings =
await _channel.invokeMethod('getSettings', args);
if (settings != null) {
settings = settings.cast<String, dynamic>();
return InAppBrowserClassSettings.fromMap(settings as Map<String, dynamic>);
}
return null;
}
///Returns `true` if the [InAppBrowser] instance is opened, otherwise `false`.
bool isOpened() {
return this._isOpened;
@ -314,9 +353,9 @@ class InAppBrowser {
///Event fired when the [InAppBrowser] encounters an error loading an [url].
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedError(android.webkit.WebView,%20int,%20java.lang.String,%20java.lang.String)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455623-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedError](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedError(android.webkit.WebView,%20int,%20java.lang.String,%20java.lang.String)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455623-webview))
void onLoadError(Uri? url, int code, String message) {}
///Event fired when the [InAppBrowser] main page receives an HTTP error.
@ -329,9 +368,9 @@ class InAppBrowser {
///
///**NOTE**: available on Android 23+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedHttpError(android.webkit.WebView,%20android.webkit.WebResourceRequest,%20android.webkit.WebResourceResponse)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedHttpError](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedHttpError(android.webkit.WebView,%20android.webkit.WebResourceRequest,%20android.webkit.WebResourceResponse)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview))
void onLoadHttpError(Uri? url, int statusCode, String description) {}
///Event fired when the current [progress] (range 0-100) of loading a page is changed.
@ -343,30 +382,36 @@ class InAppBrowser {
///Event fired when the [InAppBrowser] webview receives a [ConsoleMessage].
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onConsoleMessage(android.webkit.ConsoleMessage)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onConsoleMessage](https://developer.android.com/reference/android/webkit/WebChromeClient#onConsoleMessage(android.webkit.ConsoleMessage)))
///- iOS
void onConsoleMessage(ConsoleMessage consoleMessage) {}
///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.
///
///Note that on Android there isn't any way to load an URL for a frame that is not the main frame, so if the request is not for the main frame, the navigation is allowed by default.
///However, if you want to cancel requests for subframes, you can use the [AndroidInAppWebViewOptions.regexToCancelSubFramesLoading] option
///However, if you want to cancel requests for subframes, you can use the [InAppWebViewSettings.regexToCancelSubFramesLoading] option
///to write a Regular Expression that, if the url request of a subframe matches, then the request of that subframe is canceled.
///
///Also, on Android, this method is not called for POST requests.
///
///[navigationAction] represents an object that contains information about an action that causes navigation to occur.
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldOverrideUrlLoading] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldOverrideUrlLoading] option to `true`.
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.shouldOverrideUrlLoading](https://developer.android.com/reference/android/webkit/WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView,%20java.lang.String)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455641-webview))
Future<NavigationActionPolicy?>? shouldOverrideUrlLoading(
NavigationAction navigationAction) {}
///Event fired when the [InAppBrowser] 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`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useOnLoadResource] and [InAppWebViewSettings.javaScriptEnabled] options to `true`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
void onLoadResource(LoadedResource resource) {}
///Event fired when the [InAppBrowser] webview scrolls.
@ -375,13 +420,13 @@ class InAppBrowser {
///
///[y] represents the current vertical scroll origin in pixels.
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.onScrollChanged](https://developer.android.com/reference/android/webkit/WebView#onScrollChanged(int,%20int,%20int,%20int)))
///- iOS ([Official API - UIScrollViewDelegate.scrollViewDidScroll](https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619392-scrollviewdidscroll))
void onScrollChanged(int x, int y) {}
///Use [onDownloadStartRequest] instead
@Deprecated('Use `onDownloadStartRequest` instead')
@Deprecated('Use onDownloadStartRequest instead')
void onDownloadStart(Uri url) {}
///Event fired when [WebView] recognizes a downloadable file.
@ -389,11 +434,11 @@ class InAppBrowser {
///
///[downloadStartRequest] represents the request of the file to download.
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useOnDownloadStart] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useOnDownloadStart] option to `true`.
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.setDownloadListener](https://developer.android.com/reference/android/webkit/WebView#setDownloadListener(android.webkit.DownloadListener)))
///- iOS
void onDownloadStartRequest(DownloadStartRequest downloadStartRequest) {}
///Event fired when the [InAppBrowser] 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`.
@ -402,7 +447,9 @@ class InAppBrowser {
///
///[url] represents the url of the request.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkurlschemehandler
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS ([Official API - WKURLSchemeHandler](https://developer.apple.com/documentation/webkit/wkurlschemehandler))
Future<CustomSchemeResponse?>? onLoadResourceCustomScheme(Uri url) {}
///Event fired when the [InAppBrowser] webview requests the host application to create a new window,
@ -413,44 +460,52 @@ class InAppBrowser {
///
///[createWindowAction] represents the request.
///
///**NOTE**: to allow JavaScript to open windows, you need to set [InAppWebViewOptions.javaScriptCanOpenWindowsAutomatically] option to `true`.
///**NOTE**: to allow JavaScript to open windows, you need to set [InAppWebViewSettings.javaScriptCanOpenWindowsAutomatically] option to `true`.
///
///**NOTE**: on Android you need to set [AndroidInAppWebViewOptions.supportMultipleWindows] option to `true`.
///**NOTE**: on Android you need to set [InAppWebViewSettings.supportMultipleWindows] option to `true`.
///
///**NOTE**: on iOS, setting these initial options: [InAppWebViewOptions.supportZoom], [InAppWebViewOptions.useOnLoadResource], [InAppWebViewOptions.useShouldInterceptAjaxRequest],
///[InAppWebViewOptions.useShouldInterceptFetchRequest], [InAppWebViewOptions.applicationNameForUserAgent], [InAppWebViewOptions.javaScriptCanOpenWindowsAutomatically],
///[InAppWebViewOptions.javaScriptEnabled], [InAppWebViewOptions.minimumFontSize], [InAppWebViewOptions.preferredContentMode], [InAppWebViewOptions.incognito],
///[InAppWebViewOptions.cacheEnabled], [InAppWebViewOptions.mediaPlaybackRequiresUserGesture],
///[InAppWebViewOptions.resourceCustomSchemes], [IOSInAppWebViewOptions.sharedCookiesEnabled],
///[IOSInAppWebViewOptions.enableViewportScale], [IOSInAppWebViewOptions.allowsAirPlayForMediaPlayback],
///[IOSInAppWebViewOptions.allowsPictureInPictureMediaPlayback], [IOSInAppWebViewOptions.isFraudulentWebsiteWarningEnabled],
///[IOSInAppWebViewOptions.allowsInlineMediaPlayback], [IOSInAppWebViewOptions.suppressesIncrementalRendering], [IOSInAppWebViewOptions.selectionGranularity],
///[IOSInAppWebViewOptions.ignoresViewportScaleLimits],
///**NOTE**: on iOS, setting these initial options: [InAppWebViewSettings.supportZoom], [InAppWebViewSettings.useOnLoadResource], [InAppWebViewSettings.useShouldInterceptAjaxRequest],
///[InAppWebViewSettings.useShouldInterceptFetchRequest], [InAppWebViewSettings.applicationNameForUserAgent], [InAppWebViewSettings.javaScriptCanOpenWindowsAutomatically],
///[InAppWebViewSettings.javaScriptEnabled], [InAppWebViewSettings.minimumFontSize], [InAppWebViewSettings.preferredContentMode], [InAppWebViewSettings.incognito],
///[InAppWebViewSettings.cacheEnabled], [InAppWebViewSettings.mediaPlaybackRequiresUserGesture],
///[InAppWebViewSettings.resourceCustomSchemes], [InAppWebViewSettings.sharedCookiesEnabled],
///[InAppWebViewSettings.enableViewportScale], [InAppWebViewSettings.allowsAirPlayForMediaPlayback],
///[InAppWebViewSettings.allowsPictureInPictureMediaPlayback], [InAppWebViewSettings.isFraudulentWebsiteWarningEnabled],
///[InAppWebViewSettings.allowsInlineMediaPlayback], [InAppWebViewSettings.suppressesIncrementalRendering], [InAppWebViewSettings.selectionGranularity],
///[InAppWebViewSettings.ignoresViewportScaleLimits],
///will have no effect due to a `WKWebView` limitation when creating a new window WebView: it's impossible to return a new `WKWebView`
///with a different `WKWebViewConfiguration` instance (see https://developer.apple.com/documentation/webkit/wkuidelegate/1536907-webview).
///So, these options will be inherited from the caller WebView.
///Also, note that calling [InAppWebViewController.setOptions] method using the controller of the new created WebView,
///Also, note that calling [InAppWebViewController.setSettings] method using the controller of the new created WebView,
///it will update also the WebView options of the caller WebView.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onCreateWindow(android.webkit.WebView,%20boolean,%20boolean,%20android.os.Message)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1536907-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onCreateWindow](https://developer.android.com/reference/android/webkit/WebChromeClient#onCreateWindow(android.webkit.WebView,%20boolean,%20boolean,%20android.os.Message)))
///- iOS ([Official API - WKUIDelegate.webView](https://developer.apple.com/documentation/webkit/wkuidelegate/1536907-webview))
Future<bool?>? onCreateWindow(CreateWindowAction createWindowAction) {}
///Event fired when the host application should close the given WebView and remove it from the view system if necessary.
///At this point, WebCore has stopped any loading in this window and has removed any cross-scripting ability in javascript.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onCloseWindow(android.webkit.WebView)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1537390-webviewdidclose
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onCloseWindow](https://developer.android.com/reference/android/webkit/WebChromeClient#onCloseWindow(android.webkit.WebView)))
///- iOS ([Official API - WKUIDelegate.webViewDidClose](https://developer.apple.com/documentation/webkit/wkuidelegate/1537390-webviewdidclose))
void onCloseWindow() {}
///Event fired when the JavaScript `window` object of the WebView has received focus.
///This is the result of the `focus` javascript event applied to the `window` object.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
void onWindowFocus() {}
///Event fired when the JavaScript `window` object of the WebView has lost focus.
///This is the result of the `blur` javascript event applied to the `window` object.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
void onWindowBlur() {}
///Event fired when javascript calls the `alert()` method to display an alert dialog.
@ -458,9 +513,9 @@ class InAppBrowser {
///
///[jsAlertRequest] contains the message to be displayed in the alert dialog and the of the page requesting the dialog.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onJsAlert(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1537406-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onJsAlert](https://developer.android.com/reference/android/webkit/WebChromeClient#onJsAlert(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)))
///- iOS ([Official API - WKUIDelegate.webView](https://developer.apple.com/documentation/webkit/wkuidelegate/1537406-webview))
Future<JsAlertResponse?>? onJsAlert(JsAlertRequest jsAlertRequest) {}
///Event fired when javascript calls the `confirm()` method to display a confirm dialog.
@ -468,9 +523,9 @@ class InAppBrowser {
///
///[jsConfirmRequest] contains the message to be displayed in the confirm dialog and the of the page requesting the dialog.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onJsConfirm(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1536489-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onJsConfirm](https://developer.android.com/reference/android/webkit/WebChromeClient#onJsConfirm(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)))
///- iOS ([Official API - WKUIDelegate.webView](https://developer.apple.com/documentation/webkit/wkuidelegate/1536489-webview))
Future<JsConfirmResponse?>? onJsConfirm(JsConfirmRequest jsConfirmRequest) {}
///Event fired when javascript calls the `prompt()` method to display a prompt dialog.
@ -478,18 +533,18 @@ class InAppBrowser {
///
///[jsPromptRequest] contains the message to be displayed in the prompt dialog, the default value displayed in the prompt dialog, and the of the page requesting the dialog.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onJsPrompt(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20android.webkit.JsPromptResult)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1538086-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onJsPrompt](https://developer.android.com/reference/android/webkit/WebChromeClient#onJsPrompt(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20android.webkit.JsPromptResult)))
///- iOS ([Official API - WKUIDelegate.webView](https://developer.apple.com/documentation/webkit/wkuidelegate/1538086-webview))
Future<JsPromptResponse?>? onJsPrompt(JsPromptRequest jsPromptRequest) {}
///Event fired when the WebView received an HTTP authentication request. The default behavior is to cancel the request.
///
///[challenge] contains data about host, port, protocol, realm, etc. as specified in the [URLAuthenticationChallenge].
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedHttpAuthRequest](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedHttpAuthRequest(android.webkit.WebView,%20android.webkit.HttpAuthHandler,%20java.lang.String,%20java.lang.String)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview))
Future<HttpAuthResponse?>? onReceivedHttpAuthRequest(
URLAuthenticationChallenge challenge) {}
@ -498,9 +553,9 @@ class InAppBrowser {
///
///[challenge] contains data about host, port, protocol, realm, etc. as specified in the [ServerTrustChallenge].
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedSslError](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedSslError(android.webkit.WebView,%20android.webkit.SslErrorHandler,%20android.net.http.SslError)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview))
Future<ServerTrustAuthResponse?>? onReceivedServerTrustAuthRequest(
URLAuthenticationChallenge challenge) {}
@ -511,9 +566,9 @@ class InAppBrowser {
///
///[challenge] contains data about host, port, protocol, realm, etc. as specified in the [ClientCertChallenge].
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedClientCertRequest](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedClientCertRequest(android.webkit.WebView,%20android.webkit.ClientCertRequest)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview))
Future<ClientCertResponse?>? onReceivedClientCertRequest(
URLAuthenticationChallenge challenge) {}
@ -537,7 +592,15 @@ class InAppBrowser {
///
///[ajaxRequest] represents the `XMLHttpRequest`.
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldInterceptAjaxRequest] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptAjaxRequest] option to `true`.
///Also, unlike iOS that has [WKUserScript](https://developer.apple.com/documentation/webkit/wkuserscript) that
///can inject javascript code right after the document element is created but before any other content is loaded, in Android the javascript code
///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.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
Future<AjaxRequest?>? shouldInterceptAjaxRequest(AjaxRequest ajaxRequest) {}
///Event fired whenever the `readyState` attribute of an `XMLHttpRequest` changes.
@ -545,7 +608,15 @@ class InAppBrowser {
///
///[ajaxRequest] represents the [XMLHttpRequest].
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldInterceptAjaxRequest] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptAjaxRequest] option to `true`.
///Also, unlike iOS that has [WKUserScript](https://developer.apple.com/documentation/webkit/wkuserscript) that
///can inject javascript code right after the document element is created but before any other content is loaded, in Android the javascript code
///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.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
Future<AjaxRequestAction?>? onAjaxReadyStateChange(AjaxRequest ajaxRequest) {}
///Event fired as an `XMLHttpRequest` progress.
@ -553,7 +624,15 @@ class InAppBrowser {
///
///[ajaxRequest] represents the [XMLHttpRequest].
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldInterceptAjaxRequest] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptAjaxRequest] option to `true`.
///Also, unlike iOS that has [WKUserScript](https://developer.apple.com/documentation/webkit/wkuserscript) that
///can inject javascript code right after the document element is created but before any other content is loaded, in Android the javascript code
///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.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
Future<AjaxRequestAction?>? onAjaxProgress(AjaxRequest ajaxRequest) {}
///Event fired when a request is sent to a server through [Fetch API](https://developer.mozilla.org/it/docs/Web/API/Fetch_API).
@ -561,7 +640,15 @@ class InAppBrowser {
///
///[fetchRequest] represents a resource request.
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldInterceptFetchRequest] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptFetchRequest] option to `true`.
///Also, unlike iOS that has [WKUserScript](https://developer.apple.com/documentation/webkit/wkuserscript) that
///can inject javascript code right after the document element is created but before any other content is loaded, in Android the javascript code
///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.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
Future<FetchRequest?>? shouldInterceptFetchRequest(
FetchRequest fetchRequest) {}
@ -572,10 +659,12 @@ class InAppBrowser {
///
///[url] represents the url being visited.
///
///[androidIsReload] indicates if this url is being reloaded. Available only on Android.
///[isReload] indicates if this url is being reloaded. Available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#doUpdateVisitedHistory(android.webkit.WebView,%20java.lang.String,%20boolean)
void onUpdateVisitedHistory(Uri? url, bool? androidIsReload) {}
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.doUpdateVisitedHistory](https://developer.android.com/reference/android/webkit/WebViewClient#doUpdateVisitedHistory(android.webkit.WebView,%20java.lang.String,%20boolean)))
///- iOS
void onUpdateVisitedHistory(Uri? url, bool? isReload) {}
///Event fired when `window.print()` is called from JavaScript side.
///
@ -590,23 +679,23 @@ class InAppBrowser {
///
///[hitTestResult] represents the hit result for hitting an HTML elements.
///
///**Official Android API**: https://developer.android.com/reference/android/view/View#setOnLongClickListener(android.view.View.OnLongClickListener)
///
///**Official iOS API**: https://developer.apple.com/documentation/uikit/uilongpressgesturerecognizer
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - View.setOnLongClickListener](https://developer.android.com/reference/android/view/View#setOnLongClickListener(android.view.View.OnLongClickListener)))
///- iOS ([Official API - UILongPressGestureRecognizer](https://developer.apple.com/documentation/uikit/uilongpressgesturerecognizer))
void onLongPressHitTestResult(InAppWebViewHitTestResult hitTestResult) {}
///Event fired when the current page has entered full screen mode.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onShowCustomView(android.view.View,%20android.webkit.WebChromeClient.CustomViewCallback)
///
///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiwindow/1621621-didbecomevisiblenotification
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onShowCustomView](https://developer.android.com/reference/android/webkit/WebChromeClient#onShowCustomView(android.view.View,%20android.webkit.WebChromeClient.CustomViewCallback)))
///- iOS ([Official API - UIWindow.didBecomeVisibleNotification](https://developer.apple.com/documentation/uikit/uiwindow/1621621-didbecomevisiblenotification))
void onEnterFullscreen() {}
///Event fired when the current page has exited full screen mode.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onHideCustomView()
///
///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiwindow/1621617-didbecomehiddennotification
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onHideCustomView](https://developer.android.com/reference/android/webkit/WebChromeClient#onHideCustomView()))
///- iOS ([Official API - UIWindow.didBecomeHiddenNotification](https://developer.apple.com/documentation/uikit/uiwindow/1621617-didbecomehiddennotification))
void onExitFullscreen() {}
///Called when the web view begins to receive web content.
@ -616,16 +705,18 @@ class InAppBrowser {
///
///[url] represents the URL corresponding to the page navigation that triggered this callback.
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onPageCommitVisible](https://developer.android.com/reference/android/webkit/WebViewClient#onPageCommitVisible(android.webkit.WebView,%20java.lang.String)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455635-webview))
void onPageCommitVisible(Uri? url) {}
///Event fired when a change in the document title occurred.
///
///[title] represents the string containing the new title of the document.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedTitle(android.webkit.WebView,%20java.lang.String)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onReceivedTitle](https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedTitle(android.webkit.WebView,%20java.lang.String)))
///- iOS
void onTitleChanged(String? title) {}
///Event fired to respond to the results of an over-scroll operation.
@ -638,22 +729,27 @@ class InAppBrowser {
///
///[clampedY] is `true` if [y] was clamped to an over-scroll boundary.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#onOverScrolled(int,%20int,%20boolean,%20boolean)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.onOverScrolled](https://developer.android.com/reference/android/webkit/WebView#onOverScrolled(int,%20int,%20boolean,%20boolean)))
///- iOS
void onOverScrolled(int x, int y, bool clampedX, bool clampedY) {}
///Event fired when the zoom scale of the WebView has changed.
///
///[oldScale] The old zoom scale factor.
///
///[newScale] The new zoom scale factor.
///[newScale] The new zoom scale factor.ì
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onScaleChanged(android.webkit.WebView,%20float,%20float)
///
///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619409-scrollviewdidzoom
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onScaleChanged](https://developer.android.com/reference/android/webkit/WebViewClient#onScaleChanged(android.webkit.WebView,%20float,%20float)))
///- iOS ([Official API - UIScrollViewDelegate.scrollViewDidZoom](https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619409-scrollviewdidzoom))
void onZoomScaleChanged(double oldScale, double newScale) {}
///Use [onSafeBrowsingHit] instead.
@Deprecated("Use onSafeBrowsingHit instead")
Future<SafeBrowsingResponse?>? androidOnSafeBrowsingHit(
Uri url, SafeBrowsingThreat? threatType) {}
///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.
///
@ -663,10 +759,16 @@ class InAppBrowser {
///
///**NOTE**: available only on Android 27+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onSafeBrowsingHit(android.webkit.WebView,%20android.webkit.WebResourceRequest,%20int,%20android.webkit.SafeBrowsingResponse)
Future<SafeBrowsingResponse?>? androidOnSafeBrowsingHit(
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onSafeBrowsingHit](https://developer.android.com/reference/android/webkit/WebViewClient#onSafeBrowsingHit(android.webkit.WebView,%20android.webkit.WebResourceRequest,%20int,%20android.webkit.SafeBrowsingResponse)))
Future<SafeBrowsingResponse?>? onSafeBrowsingHit(
Uri url, SafeBrowsingThreat? threatType) {}
///Use [onPermissionRequest] instead.
@Deprecated("Use onPermissionRequest instead")
Future<PermissionRequestResponse?>? androidOnPermissionRequest(
String origin, List<String> resources) {}
///Event fired when the WebView is requesting permission to access the specified resources and the permission currently isn't granted or denied.
///
///[origin] represents the origin of the web page which is trying to access the restricted resources.
@ -675,29 +777,42 @@ class InAppBrowser {
///
///**NOTE**: available only on Android 23+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onPermissionRequest(android.webkit.PermissionRequest)
Future<PermissionRequestResponse?>? androidOnPermissionRequest(
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onPermissionRequest](https://developer.android.com/reference/android/webkit/WebChromeClient#onPermissionRequest(android.webkit.PermissionRequest)))
Future<PermissionRequestResponse?>? onPermissionRequest(
String origin, List<String> resources) {}
///Use [onGeolocationPermissionsShowPrompt] instead.
@Deprecated("Use onGeolocationPermissionsShowPrompt instead")
Future<GeolocationPermissionShowPromptResponse?>?
androidOnGeolocationPermissionsShowPrompt(String origin) {}
///Event that notifies the host application that web content from the specified origin is attempting to use the Geolocation API, but no permission state is currently set for that origin.
///Note that for applications targeting Android N and later SDKs (API level > `Build.VERSION_CODES.M`) this method is only called for requests originating from secure origins such as https.
///On non-secure origins geolocation requests are automatically denied.
///
///[origin] represents the origin of the web content attempting to use the Geolocation API.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String,%20android.webkit.GeolocationPermissions.Callback)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onGeolocationPermissionsShowPrompt](https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String,%20android.webkit.GeolocationPermissions.Callback)))
Future<GeolocationPermissionShowPromptResponse?>?
androidOnGeolocationPermissionsShowPrompt(String origin) {}
onGeolocationPermissionsShowPrompt(String origin) {}
///Notify the host application that a request for Geolocation permissions, made with a previous call to [androidOnGeolocationPermissionsShowPrompt] has been canceled.
///Use [onGeolocationPermissionsHidePrompt] instead.
@Deprecated("Use onGeolocationPermissionsHidePrompt instead")
void androidOnGeolocationPermissionsHidePrompt() {}
///Notify the host application that a request for Geolocation permissions, made with a previous call to [onGeolocationPermissionsShowPrompt] has been canceled.
///Any related UI should therefore be hidden.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsHidePrompt()
void androidOnGeolocationPermissionsHidePrompt() {}
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onGeolocationPermissionsHidePrompt](https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsHidePrompt()))
void onGeolocationPermissionsHidePrompt() {}
///Use [shouldInterceptRequest] instead.
@Deprecated("Use shouldInterceptRequest instead")
Future<WebResourceResponse?>? androidShouldInterceptRequest(
WebResourceRequest request) {}
///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.
@ -711,38 +826,48 @@ class InAppBrowser {
///
///[request] Object containing the details of the request.
///
///**NOTE**: available only on Android.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptRequest] option to `true`.
///
///**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)
Future<WebResourceResponse?>? androidShouldInterceptRequest(
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.shouldInterceptRequest](https://developer.android.com/reference/android/webkit/WebViewClient#shouldInterceptRequest(android.webkit.WebView,%20android.webkit.WebResourceRequest)))
Future<WebResourceResponse?>? shouldInterceptRequest(
WebResourceRequest request) {}
///Use [onRenderProcessUnresponsive] instead.
@Deprecated("Use onRenderProcessUnresponsive instead")
Future<WebViewRenderProcessAction?>? androidOnRenderProcessUnresponsive(
Uri? url) {}
///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.
///
///If a WebView fails to process an input event, or successfully navigate to a new URL within a reasonable time frame, the renderer is considered to be unresponsive, and this callback will be called.
///
///This callback will continue to be called at regular intervals as long as the renderer remains unresponsive.
///If the renderer becomes responsive again, [androidOnRenderProcessResponsive] will be called once,
///If the renderer becomes responsive again, [onRenderProcessResponsive] will be called once,
///and this method will not subsequently be called unless another period of unresponsiveness is detected.
///
///The minimum interval between successive calls to `androidOnRenderProcessUnresponsive` is 5 seconds.
///The minimum interval between successive calls to [onRenderProcessUnresponsive] is 5 seconds.
///
///No action is taken by WebView as a result of this method call.
///Applications may choose to terminate the associated renderer via the object that is passed to this callback,
///if in multiprocess mode, however this must be accompanied by correctly handling [androidOnRenderProcessGone] for this WebView,
///if in multiprocess mode, however this must be accompanied by correctly handling [onRenderProcessGone] for this WebView,
///and all other WebViews associated with the same renderer. Failure to do so will result in application termination.
///
///**NOTE**: available only on Android 29+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessUnresponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess)
Future<WebViewRenderProcessAction?>? androidOnRenderProcessUnresponsive(
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewRenderProcessClient.onRenderProcessUnresponsive](https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessUnresponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess)))
Future<WebViewRenderProcessAction?>? onRenderProcessUnresponsive(
Uri? url) {}
///Use [onRenderProcessResponsive] instead.
@Deprecated("Use onRenderProcessResponsive instead")
Future<WebViewRenderProcessAction?>? androidOnRenderProcessResponsive(
Uri? url) {}
///Event called once when an unresponsive renderer currently associated with the WebView becomes responsive.
///
///After a WebView renderer becomes unresponsive, which is notified to the application by [androidOnRenderProcessUnresponsive],
///After a WebView renderer becomes unresponsive, which is notified to the application by [onRenderProcessUnresponsive],
///it is possible for the blocking renderer task to complete, returning the renderer to a responsive state.
///In that case, this method is called once to indicate responsiveness.
///
@ -750,10 +875,15 @@ class InAppBrowser {
///
///**NOTE**: available only on Android 29+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessResponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess)
Future<WebViewRenderProcessAction?>? androidOnRenderProcessResponsive(
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewRenderProcessClient.onRenderProcessResponsive](https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessResponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess)))
Future<WebViewRenderProcessAction?>? onRenderProcessResponsive(
Uri? url) {}
///Use [onRenderProcessGone] instead.
@Deprecated("Use onRenderProcessGone instead")
void androidOnRenderProcessGone(RenderProcessGoneDetail detail) {}
///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.
///The WebView should be removed from the view hierarchy, all references to it should be cleaned up.
@ -762,28 +892,40 @@ class InAppBrowser {
///
///**NOTE**: available only on Android 26+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onRenderProcessGone(android.webkit.WebView,%20android.webkit.RenderProcessGoneDetail)
void androidOnRenderProcessGone(RenderProcessGoneDetail detail) {}
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onRenderProcessGone](https://developer.android.com/reference/android/webkit/WebViewClient#onRenderProcessGone(android.webkit.WebView,%20android.webkit.RenderProcessGoneDetail)))
void onRenderProcessGone(RenderProcessGoneDetail detail) {}
///Use [onFormResubmission] instead.
@Deprecated('Use onFormResubmission instead')
Future<FormResubmissionAction?>? androidOnFormResubmission(Uri? url) {}
///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)
Future<FormResubmissionAction?>? androidOnFormResubmission(Uri? url) {}
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onFormResubmission](https://developer.android.com/reference/android/webkit/WebViewClient#onFormResubmission(android.webkit.WebView,%20android.os.Message,%20android.os.Message)))
Future<FormResubmissionAction?>? onFormResubmission(Uri? url) {}
///Use [onZoomScaleChanged] instead.
@Deprecated('Use `onZoomScaleChanged` instead')
@Deprecated('Use onZoomScaleChanged instead')
void androidOnScaleChanged(double oldScale, double newScale) {}
///Use [onReceivedIcon] instead.
@Deprecated('Use onReceivedIcon instead')
void androidOnReceivedIcon(Uint8List icon) {}
///Event fired when there is new favicon for the current page.
///
///[icon] represents the favicon for the current page.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedIcon(android.webkit.WebView,%20android.graphics.Bitmap)
void androidOnReceivedIcon(Uint8List icon) {}
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onReceivedIcon](https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedIcon(android.webkit.WebView,%20android.graphics.Bitmap)))
void onReceivedIcon(Uint8List icon) {}
///Use [onReceivedTouchIconUrl] instead.
@Deprecated('Use onReceivedTouchIconUrl instead')
void androidOnReceivedTouchIconUrl(Uri url, bool precomposed) {}
///Event fired when there is an url for an apple-touch-icon.
///
@ -791,10 +933,15 @@ class InAppBrowser {
///
///[precomposed] is `true` if the url is for a precomposed touch icon.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedTouchIconUrl(android.webkit.WebView,%20java.lang.String,%20boolean)
void androidOnReceivedTouchIconUrl(Uri url, bool precomposed) {}
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onReceivedTouchIconUrl](https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedTouchIconUrl(android.webkit.WebView,%20java.lang.String,%20boolean)))
void onReceivedTouchIconUrl(Uri url, bool precomposed) {}
///Use [onJsBeforeUnload] instead.
@Deprecated('Use onJsBeforeUnload instead')
Future<JsBeforeUnloadResponse?>? androidOnJsBeforeUnload(
JsBeforeUnloadRequest jsBeforeUnloadRequest) {}
///Event fired when the client should display a dialog to confirm navigation away from the current page.
///This is the result of the `onbeforeunload` javascript event.
@ -806,44 +953,63 @@ class InAppBrowser {
///
///[jsBeforeUnloadRequest] contains the message to be displayed in the alert dialog and the of the page requesting the dialog.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onJsBeforeUnload(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)
Future<JsBeforeUnloadResponse?>? androidOnJsBeforeUnload(
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onJsBeforeUnload](https://developer.android.com/reference/android/webkit/WebChromeClient#onJsBeforeUnload(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)))
Future<JsBeforeUnloadResponse?>? onJsBeforeUnload(
JsBeforeUnloadRequest jsBeforeUnloadRequest) {}
///Use [onReceivedLoginRequest] instead.
@Deprecated('Use onReceivedLoginRequest instead')
void androidOnReceivedLoginRequest(LoginRequest loginRequest) {}
///Event fired when a request to automatically log in the user has been processed.
///
///[loginRequest] contains the realm, account and args of the login request.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedLoginRequest(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20java.lang.String)
void androidOnReceivedLoginRequest(LoginRequest loginRequest) {}
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedLoginRequest](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedLoginRequest(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20java.lang.String)))
void onReceivedLoginRequest(LoginRequest loginRequest) {}
///Use [onWebContentProcessDidTerminate] instead.
@Deprecated('Use onWebContentProcessDidTerminate instead')
void iosOnWebContentProcessDidTerminate() {}
///Invoked when the web view's web content process is terminated.
///
///**NOTE**: available only on iOS.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455639-webviewwebcontentprocessdidtermi
void iosOnWebContentProcessDidTerminate() {}
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKNavigationDelegate.webViewWebContentProcessDidTerminate](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455639-webviewwebcontentprocessdidtermi))
void onWebContentProcessDidTerminate() {}
///Use [onDidReceiveServerRedirectForProvisionalNavigation] instead.
@Deprecated('Use onDidReceiveServerRedirectForProvisionalNavigation instead')
void iosOnDidReceiveServerRedirectForProvisionalNavigation() {}
///Called when a web view receives a server redirect.
///
///**NOTE**: available only on iOS.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455627-webview
void iosOnDidReceiveServerRedirectForProvisionalNavigation() {}
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455627-webview))
void onDidReceiveServerRedirectForProvisionalNavigation() {}
///Use [onNavigationResponse] instead.
@Deprecated('Use onNavigationResponse instead')
Future<IOSNavigationResponseAction?>? iosOnNavigationResponse(
IOSWKNavigationResponse navigationResponse) {}
///Called when a web view asks for permission to navigate to new content after the response to the navigation request is known.
///
///[navigationResponse] represents the navigation response.
///
///**NOTE**: available only on iOS.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useOnNavigationResponse] option to `true`.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview
Future<IOSNavigationResponseAction?>? iosOnNavigationResponse(
IOSWKNavigationResponse navigationResponse) {}
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview))
Future<NavigationResponseAction?>? onNavigationResponse(
NavigationResponse navigationResponse) {}
///Use [shouldAllowDeprecatedTLS] instead.
@Deprecated('Use shouldAllowDeprecatedTLS instead')
Future<IOSShouldAllowDeprecatedTLSAction?>? iosShouldAllowDeprecatedTLS(
URLAuthenticationChallenge challenge) {}
///Called when a web view asks whether to continue with a connection that uses a deprecated version of TLS (v1.0 and v1.1).
///
@ -851,8 +1017,9 @@ class InAppBrowser {
///
///**NOTE**: available only on iOS 14.0+.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/3601237-webview
Future<IOSShouldAllowDeprecatedTLSAction?>? iosShouldAllowDeprecatedTLS(
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/3601237-webview))
Future<ShouldAllowDeprecatedTLSAction?>? shouldAllowDeprecatedTLS(
URLAuthenticationChallenge challenge) {}
void throwIfAlreadyOpened({String message = ''}) {

View File

@ -8,24 +8,20 @@ import '../util.dart';
import '../in_app_webview/in_app_webview_settings.dart';
import 'android/in_app_browser_options.dart';
import '../in_app_webview/android/in_app_webview_settings.dart';
import '../in_app_webview/android/in_app_webview_options.dart';
import 'ios/in_app_browser_settings.dart';
import '../in_app_webview/ios/in_app_webview_settings.dart';
import 'ios/in_app_browser_options.dart';
import '../in_app_webview/ios/in_app_webview_options.dart';
class BrowserOptions {
Map<String, dynamic> toMap() {
return {};
}
static BrowserOptions fromMap(Map<String, dynamic> map, {BrowserOptions? instance}) {
static BrowserOptions fromMap(Map<String, dynamic> map) {
return BrowserOptions();
}
static Map<String, dynamic> instanceToMap(BrowserOptions options) {
return options.toMap();
}
BrowserOptions copy() {
return BrowserOptions.fromMap(this.toMap());
}
@ -40,25 +36,25 @@ class BrowserOptions {
}
}
///Class that represents the settings that can be used for an [InAppBrowser] WebView.
///Class that represents the settings that can be used for an [InAppBrowser] instance.
class InAppBrowserClassSettings {
///Browser settings.
late InAppBrowserSettings settings;
late InAppBrowserSettings browserSettings;
///WebView settings.
late InAppWebViewSettings webViewSettings;
InAppBrowserClassSettings(
{InAppBrowserSettings? settings,
{InAppBrowserSettings? browserSettings,
InAppWebViewSettings? webViewSettings}) {
this.settings = settings ?? InAppBrowserSettings();
this.browserSettings = browserSettings ?? InAppBrowserSettings();
this.webViewSettings = webViewSettings ?? InAppWebViewSettings();
}
Map<String, dynamic> toMap() {
Map<String, dynamic> options = {};
options.addAll(this.settings.toMap());
options.addAll(this.browserSettings.toMap());
options.addAll(this.webViewSettings.toMap());
return options;
@ -81,7 +77,7 @@ class InAppBrowserClassSettings {
if (instance == null) {
instance = InAppBrowserClassSettings();
}
instance.settings = InAppBrowserSettings.fromMap(options);
instance.browserSettings = InAppBrowserSettings.fromMap(options);
instance.webViewSettings = InAppWebViewSettings.fromMap(options);
return instance;
}
@ -91,80 +87,216 @@ class InAppBrowserClassSettings {
}
}
class InAppBrowserSettings extends InAppBrowserOptions implements AndroidInAppBrowserOptions, IOSInAppBrowserOptions {
@override
bool allowGoBackWithBackButton;
///This class represents all [InAppBrowser] settings available.
class InAppBrowserSettings implements BrowserOptions, AndroidOptions, IosOptions {
@override
String? closeButtonCaption;
///Set to `true` to create the browser and load the page, but not show it. Omit or set to `false` to have the browser open and load normally.
///The default value is `false`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
bool hidden;
@override
Color? closeButtonColor;
///Set to `true` to hide the toolbar at the top of the WebView. The default value is `false`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
bool hideToolbarTop;
@override
bool closeOnCannotGoBack;
///Set the custom background color of the toolbar at the top.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
Color? toolbarTopBackgroundColor;
@override
///Set to `true` to hide the url bar on the toolbar at the top. The default value is `false`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
bool hideUrlBar;
///Set to `true` to hide the progress bar when the WebView is loading a page. The default value is `false`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
bool hideProgressBar;
///Set to `true` if you want the title should be displayed. The default value is `false`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
bool hideTitleBar;
@override
bool hideToolbarBottom;
@override
IOSUIModalPresentationStyle presentationStyle;
@override
bool shouldCloseOnBackButtonPressed;
@override
Color? toolbarBottomBackgroundColor;
@override
Color? toolbarBottomTintColor;
@override
bool toolbarBottomTranslucent;
@override
Color? toolbarTopBarTintColor;
@override
///Set the action bar's title.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
String? toolbarTopFixedTitle;
@override
Color? toolbarTopTintColor;
///Set to `false` to not close the InAppBrowser when the user click on the Android back button and the WebView cannot go back to the history. The default value is `true`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
bool closeOnCannotGoBack;
@override
///Set to `false` to block the InAppBrowser WebView going back when the user click on the Android back button. The default value is `true`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
bool allowGoBackWithBackButton;
///Set to `true` to close the InAppBrowser when the user click on the Android back button. The default value is `false`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
bool shouldCloseOnBackButtonPressed;
///Set to `true` to set the toolbar at the top translucent. The default value is `true`.
///
///**Supported Platforms/Implementations**:
///- iOS
bool toolbarTopTranslucent;
///Set the tint color to apply to the navigation bar background.
///
///**Supported Platforms/Implementations**:
///- iOS
Color? toolbarTopBarTintColor;
///Set the tint color to apply to the navigation items and bar button items.
///
///**Supported Platforms/Implementations**:
///- iOS
Color? toolbarTopTintColor;
///Set to `true` to hide the toolbar at the bottom of the WebView. The default value is `false`.
///
///**Supported Platforms/Implementations**:
///- iOS
bool hideToolbarBottom;
///Set the custom background color of the toolbar at the bottom.
///
///**Supported Platforms/Implementations**:
///- iOS
Color? toolbarBottomBackgroundColor;
///Set the tint color to apply to the bar button items.
///
///**Supported Platforms/Implementations**:
///- iOS
Color? toolbarBottomTintColor;
///Set to `true` to set the toolbar at the bottom translucent. The default value is `true`.
///
///**Supported Platforms/Implementations**:
///- iOS
bool toolbarBottomTranslucent;
///Set the custom text for the close button.
///
///**Supported Platforms/Implementations**:
///- iOS
String? closeButtonCaption;
///Set the custom color for the close button.
///
///**Supported Platforms/Implementations**:
///- iOS
Color? closeButtonColor;
///Set the custom modal presentation style when presenting the WebView. The default value is [ModalPresentationStyle.FULL_SCREEN].
///
///**Supported Platforms/Implementations**:
///- iOS
ModalPresentationStyle presentationStyle;
///Set to the custom transition style when presenting the WebView. The default value is [ModalTransitionStyle.COVER_VERTICAL].
///
///**Supported Platforms/Implementations**:
///- iOS
ModalTransitionStyle transitionStyle;
InAppBrowserSettings(
{this.hidden = false,
this.hideToolbarTop = false,
this.toolbarTopBackgroundColor,
this.hideUrlBar = false,
this.hideProgressBar = false,
this.toolbarTopTranslucent = true,
this.toolbarTopTintColor,
this.hideToolbarBottom = false,
this.toolbarBottomBackgroundColor,
this.toolbarBottomTintColor,
this.toolbarBottomTranslucent = true,
this.closeButtonCaption,
this.closeButtonColor,
this.presentationStyle = ModalPresentationStyle.FULL_SCREEN,
this.transitionStyle = ModalTransitionStyle.COVER_VERTICAL,
this.hideTitleBar = false,
this.toolbarTopFixedTitle,
this.closeOnCannotGoBack = true,
this.allowGoBackWithBackButton = true,
this.shouldCloseOnBackButtonPressed = false});
@override
IOSUIModalTransitionStyle transitionStyle;
Map<String, dynamic> toMap() {
Map<String, dynamic> options = {};
// ignore: deprecated_member_use_from_same_package
options.addAll(InAppBrowserOptions.instanceToMap(this));
options.addAll(AndroidInAppBrowserSettings.instanceToMap(this));
options.addAll(IOSInAppBrowserSettings.instanceToMap(this));
return options;
return {
"hidden": hidden,
"hideToolbarTop": hideToolbarTop,
"toolbarTopBackgroundColor": toolbarTopBackgroundColor?.toHex(),
"hideUrlBar": hideUrlBar,
"hideProgressBar": hideProgressBar,
"hideTitleBar": hideTitleBar,
"toolbarTopFixedTitle": toolbarTopFixedTitle,
"closeOnCannotGoBack": closeOnCannotGoBack,
"allowGoBackWithBackButton": allowGoBackWithBackButton,
"shouldCloseOnBackButtonPressed": shouldCloseOnBackButtonPressed,
"toolbarTopTranslucent": toolbarTopTranslucent,
"toolbarTopTintColor": toolbarTopTintColor?.toHex(),
"hideToolbarBottom": hideToolbarBottom,
"toolbarBottomBackgroundColor": toolbarBottomBackgroundColor?.toHex(),
"toolbarBottomTintColor": toolbarBottomTintColor?.toHex(),
"toolbarBottomTranslucent": toolbarBottomTranslucent,
"closeButtonCaption": closeButtonCaption,
"closeButtonColor": closeButtonColor?.toHex(),
"presentationStyle": presentationStyle.toValue(),
"transitionStyle": transitionStyle.toValue(),
};
}
static Map<String, dynamic> instanceToMap(InAppBrowserSettings settings) {
return settings.toMap();
}
static InAppBrowserSettings fromMap(Map<String, dynamic> options, {InAppBrowserSettings? instance}) {
if (instance == null) {
instance = InAppBrowserSettings();
}
// ignore: deprecated_member_use_from_same_package
InAppBrowserOptions.fromMap(options, instance: instance);
if (defaultTargetPlatform == TargetPlatform.android) {
AndroidInAppBrowserSettings.fromMap(options, instance: instance);
}
else if (defaultTargetPlatform == TargetPlatform.iOS) {
IOSInAppBrowserSettings.fromMap(options, instance: instance);
}
static InAppBrowserSettings fromMap(Map<String, dynamic> map) {
var instance = InAppBrowserSettings();
instance.hidden = map["hidden"];
instance.hideToolbarTop = map["hideToolbarTop"];
instance.toolbarTopBackgroundColor =
UtilColor.fromHex(map["toolbarTopBackgroundColor"]);
instance.hideUrlBar = map["hideUrlBar"];
instance.hideProgressBar = map["hideProgressBar"];
instance.hideTitleBar = map["hideTitleBar"];
instance.toolbarTopFixedTitle = map["toolbarTopFixedTitle"];
instance.closeOnCannotGoBack = map["closeOnCannotGoBack"];
instance.allowGoBackWithBackButton = map["allowGoBackWithBackButton"];
instance.shouldCloseOnBackButtonPressed = map["shouldCloseOnBackButtonPressed"];
instance.toolbarTopTranslucent = map["toolbarTopTranslucent"];
instance.toolbarTopTintColor = UtilColor.fromHex(map["toolbarTopTintColor"]);
instance.hideToolbarBottom = map["hideToolbarBottom"];
instance.toolbarBottomBackgroundColor =
UtilColor.fromHex(map["toolbarBottomBackgroundColor"]);
instance.toolbarBottomTintColor =
UtilColor.fromHex(map["toolbarBottomTintColor"]);
instance.toolbarBottomTranslucent = map["toolbarBottomTranslucent"];
instance.closeButtonCaption = map["closeButtonCaption"];
instance.closeButtonColor = UtilColor.fromHex(map["closeButtonColor"]);
instance.presentationStyle =
ModalPresentationStyle.fromValue(map["presentationStyle"])!;
instance.transitionStyle =
ModalTransitionStyle.fromValue(map["transitionStyle"])!;
return instance;
}
@ -267,6 +399,8 @@ class InAppBrowserClassOptions {
}
///This class represents all the cross-platform [InAppBrowser] options available.
///Use [InAppBrowserClassSettings] instead.
@Deprecated('Use InAppBrowserClassSettings instead')
class InAppBrowserOptions
implements BrowserOptions, AndroidOptions, IosOptions {
///Set to `true` to create the browser and load the page, but not show it. Omit or set to `false` to have the browser open and load normally.
@ -304,14 +438,14 @@ class InAppBrowserOptions
}
static InAppBrowserOptions fromMap(Map<String, dynamic> map) {
InAppBrowserOptions options = InAppBrowserOptions();
options.hidden = map["hidden"];
options.hideToolbarTop = map["hideToolbarTop"];
options.toolbarTopBackgroundColor =
var instance = InAppBrowserOptions();
instance.hidden = map["hidden"];
instance.hideToolbarTop = map["hideToolbarTop"];
instance.toolbarTopBackgroundColor =
UtilColor.fromHex(map["toolbarTopBackgroundColor"]);
options.hideUrlBar = map["hideUrlBar"];
options.hideProgressBar = map["hideProgressBar"];
return options;
instance.hideUrlBar = map["hideUrlBar"];
instance.hideProgressBar = map["hideProgressBar"];
return instance;
}
@override

View File

@ -1,4 +1,4 @@
export 'in_app_browser.dart';
export 'in_app_browser_options.dart';
export 'in_app_browser_settings.dart';
export 'android/main.dart';
export 'ios/main.dart';

View File

@ -1,22 +1,14 @@
import 'dart:async';
import 'dart:core';
import 'package:flutter/services.dart';
import '../_static_channel.dart';
import '../../types.dart';
import '../../android/webview_feature.dart';
import '../in_app_webview_controller.dart';
///Class represents the Android controller that contains only android-specific methods for the WebView.
class AndroidInAppWebViewController {
///Class mixin that contains only Android-specific methods for the WebView.
abstract class AndroidInAppWebViewControllerMixin {
late MethodChannel _channel;
static MethodChannel _staticChannel = IN_APP_WEBVIEW_STATIC_CHANNEL;
AndroidInAppWebViewController({required MethodChannel channel}) {
this._channel = channel;
}
///Starts Safe Browsing initialization.
///
@ -28,7 +20,8 @@ class AndroidInAppWebViewController {
///
///This method should only be called if [AndroidWebViewFeature.isFeatureSupported] returns `true` for [AndroidWebViewFeature.START_SAFE_BROWSING].
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#startSafeBrowsing(android.content.Context,%20android.webkit.ValueCallback%3Cjava.lang.Boolean%3E)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.startSafeBrowsing](https://developer.android.com/reference/android/webkit/WebView#startSafeBrowsing(android.content.Context,%20android.webkit.ValueCallback%3Cjava.lang.Boolean%3E)))
Future<bool> startSafeBrowsing() async {
Map<String, dynamic> args = <String, dynamic>{};
return await _channel.invokeMethod('startSafeBrowsing', args);
@ -36,7 +29,8 @@ class AndroidInAppWebViewController {
///Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#clearSslPreferences()
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.clearSslPreferences](https://developer.android.com/reference/android/webkit/WebView#clearSslPreferences()))
Future<void> clearSslPreferences() async {
Map<String, dynamic> args = <String, dynamic>{};
await _channel.invokeMethod('clearSslPreferences', args);
@ -45,7 +39,8 @@ class AndroidInAppWebViewController {
///Does a best-effort attempt to pause any processing that can be paused safely, such as animations and geolocation. Note that this call does not pause JavaScript.
///To pause JavaScript globally, use [InAppWebViewController.pauseTimers]. To resume WebView, call [resume].
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#onPause()
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.onPause](https://developer.android.com/reference/android/webkit/WebView#onPause()))
Future<void> pause() async {
Map<String, dynamic> args = <String, dynamic>{};
await _channel.invokeMethod('pause', args);
@ -53,26 +48,20 @@ class AndroidInAppWebViewController {
///Resumes a WebView after a previous call to [pause].
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#onResume()
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.onResume](https://developer.android.com/reference/android/webkit/WebView#onResume()))
Future<void> resume() async {
Map<String, dynamic> args = <String, dynamic>{};
await _channel.invokeMethod('resume', args);
}
///Use [InAppWebViewController.getOriginalUrl] instead.
@Deprecated('Use `InAppWebViewController.getOriginalUrl` instead')
Future<Uri?> getOriginalUrl() async {
Map<String, dynamic> args = <String, dynamic>{};
String? url = await _channel.invokeMethod('getOriginalUrl', args);
return url != null ? Uri.parse(url) : null;
}
///Scrolls the contents of this WebView down by half the page size.
///Returns `true` if the page was scrolled.
///
///[bottom] `true` to jump to bottom of page.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#pageDown(boolean)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.pageDown](https://developer.android.com/reference/android/webkit/WebView#pageDown(boolean)))
Future<bool> pageDown({required bool bottom}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("bottom", () => bottom);
@ -82,9 +71,10 @@ class AndroidInAppWebViewController {
///Scrolls the contents of this WebView up by half the view size.
///Returns `true` if the page was scrolled.
///
///[bottom] `true` to jump to the top of the page.
///[top] `true` to jump to the top of the page.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#pageUp(boolean)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.pageUp](https://developer.android.com/reference/android/webkit/WebView#pageUp(boolean)))
Future<bool> pageUp({required bool top}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("top", () => top);
@ -94,7 +84,8 @@ class AndroidInAppWebViewController {
///Performs zoom in in this WebView.
///Returns `true` if zoom in succeeds, `false` if no zoom changes.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#zoomIn()
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.zoomIn](https://developer.android.com/reference/android/webkit/WebView#zoomIn()))
Future<bool> zoomIn() async {
Map<String, dynamic> args = <String, dynamic>{};
return await _channel.invokeMethod('zoomIn', args);
@ -103,7 +94,8 @@ class AndroidInAppWebViewController {
///Performs zoom out in this WebView.
///Returns `true` if zoom out succeeds, `false` if no zoom changes.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#zoomOut()
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.zoomOut](https://developer.android.com/reference/android/webkit/WebView#zoomOut()))
Future<bool> zoomOut() async {
Map<String, dynamic> args = <String, dynamic>{};
return await _channel.invokeMethod('zoomOut', args);
@ -112,95 +104,60 @@ class AndroidInAppWebViewController {
///Clears the internal back/forward list.
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.clearHistory](https://developer.android.com/reference/android/webkit/WebView#clearHistory())).
///- Android native WebView ([Official API - WebView.clearHistory](https://developer.android.com/reference/android/webkit/WebView#clearHistory()))
Future<void> clearHistory() async {
Map<String, dynamic> args = <String, dynamic>{};
return await _channel.invokeMethod('clearHistory', args);
}
}
///Clears the client certificate preferences stored in response to proceeding/cancelling client cert requests.
///Note that WebView automatically clears these preferences when the system keychain is updated.
///The preferences are shared by all the WebViews that are created by the embedder application.
///
///**NOTE**: On iOS certificate-based credentials are never stored permanently.
///
///**NOTE**: available on Android 21+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#clearClientCertPreferences(java.lang.Runnable)
///Use [InAppWebViewController] instead.
@Deprecated("Use InAppWebViewController instead")
class AndroidInAppWebViewController with AndroidInAppWebViewControllerMixin {
late MethodChannel _channel;
AndroidInAppWebViewController({required MethodChannel channel}) {
this._channel = channel;
}
///Use [InAppWebViewController.clearClientCertPreferences] instead.
@Deprecated("Use InAppWebViewController.clearClientCertPreferences instead")
static Future<void> clearClientCertPreferences() async {
Map<String, dynamic> args = <String, dynamic>{};
await _staticChannel.invokeMethod('clearClientCertPreferences', args);
await InAppWebViewController.clearClientCertPreferences();
}
///Returns a URL pointing to the privacy policy for Safe Browsing reporting.
///
///This method should only be called if [AndroidWebViewFeature.isFeatureSupported] returns `true` for [AndroidWebViewFeature.SAFE_BROWSING_PRIVACY_POLICY_URL].
///
///**Official Android API**: https://developer.android.com/reference/androidx/webkit/WebViewCompat#getSafeBrowsingPrivacyPolicyUrl()
///Use [InAppWebViewController.getSafeBrowsingPrivacyPolicyUrl] instead.
@Deprecated("Use InAppWebViewController.getSafeBrowsingPrivacyPolicyUrl instead")
static Future<Uri?> getSafeBrowsingPrivacyPolicyUrl() async {
Map<String, dynamic> args = <String, dynamic>{};
String? url = await _staticChannel.invokeMethod(
'getSafeBrowsingPrivacyPolicyUrl', args);
return url != null ? Uri.parse(url) : null;
return await InAppWebViewController.getSafeBrowsingPrivacyPolicyUrl();
}
///Sets the list of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. The list is global for all the WebViews.
///
/// Each rule should take one of these:
///| Rule | Example | Matches Subdomain |
///| -- | -- | -- |
///| HOSTNAME | example.com | Yes |
///| .HOSTNAME | .example.com | No |
///| IPV4_LITERAL | 192.168.1.1 | No |
///| IPV6_LITERAL_WITH_BRACKETS | [10:20:30:40:50:60:70:80] | No |
///
///All other rules, including wildcards, are invalid. The correct syntax for hosts is defined by [RFC 3986](https://tools.ietf.org/html/rfc3986#section-3.2.2).
///
///This method should only be called if [AndroidWebViewFeature.isFeatureSupported] returns `true` for [AndroidWebViewFeature.SAFE_BROWSING_ALLOWLIST].
///
///[hosts] represents the list of hosts. This value must never be `null`.
///
///**Official Android API**: https://developer.android.com/reference/androidx/webkit/WebViewCompat#setSafeBrowsingAllowlist(java.util.Set%3Cjava.lang.String%3E,%20android.webkit.ValueCallback%3Cjava.lang.Boolean%3E)
///Use [InAppWebViewController.setSafeBrowsingWhitelist] instead.
@Deprecated("Use InAppWebViewController.setSafeBrowsingWhitelist instead")
static Future<bool> setSafeBrowsingWhitelist(
{required List<String> hosts}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('hosts', () => hosts);
return await _staticChannel.invokeMethod('setSafeBrowsingWhitelist', args);
return await InAppWebViewController.setSafeBrowsingWhitelist(hosts: hosts);
}
///If WebView has already been loaded into the current process this method will return the package that was used to load it.
///Otherwise, the package that would be used if the WebView was loaded right now will be returned;
///this does not cause WebView to be loaded, so this information may become outdated at any time.
///The WebView package changes either when the current WebView package is updated, disabled, or uninstalled.
///It can also be changed through a Developer Setting. If the WebView package changes, any app process that
///has loaded WebView will be killed.
///The next time the app starts and loads WebView it will use the new WebView package instead.
///
///**NOTE**: available only on Android 21+.
///
///**Official Android API**: https://developer.android.com/reference/androidx/webkit/WebViewCompat#getCurrentWebViewPackage(android.content.Context)
///Use [InAppWebViewController.getCurrentWebViewPackage] instead.
@Deprecated("Use InAppWebViewController.getCurrentWebViewPackage instead")
static Future<AndroidWebViewPackageInfo?> getCurrentWebViewPackage() async {
Map<String, dynamic> args = <String, dynamic>{};
Map<String, dynamic>? packageInfo =
(await _staticChannel.invokeMethod('getCurrentWebViewPackage', args))
?.cast<String, dynamic>();
Map<String, dynamic>? packageInfo = (await InAppWebViewController.getCurrentWebViewPackage())?.toMap();
return AndroidWebViewPackageInfo.fromMap(packageInfo);
}
///Enables debugging of web contents (HTML / CSS / JavaScript) loaded into any WebViews of this application.
///This flag can be enabled in order to facilitate debugging of web layouts and JavaScript code running inside WebViews.
///Please refer to WebView documentation for the debugging guide. The default is `false`.
///
///[debuggingEnabled] whether to enable web contents debugging.
///
///**NOTE**: available only on Android 19+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#setWebContentsDebuggingEnabled(boolean)
///Use [InAppWebViewController.setWebContentsDebuggingEnabled] instead.
@Deprecated("Use InAppWebViewController.setWebContentsDebuggingEnabled instead")
static Future<void> setWebContentsDebuggingEnabled(
bool debuggingEnabled) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('debuggingEnabled', () => debuggingEnabled);
return await _staticChannel.invokeMethod(
'setWebContentsDebuggingEnabled', args);
return await InAppWebViewController.setWebContentsDebuggingEnabled(debuggingEnabled);
}
}
///Use [InAppWebViewController.getOriginalUrl] instead.
@Deprecated('Use InAppWebViewController.getOriginalUrl instead')
Future<Uri?> getOriginalUrl() async {
Map<String, dynamic> args = <String, dynamic>{};
String? url = await _channel.invokeMethod('getOriginalUrl', args);
return url != null ? Uri.parse(url) : null;
}
}

View File

@ -9,7 +9,7 @@ import '../context_menu.dart';
import '../types.dart';
import 'webview.dart';
import 'in_app_webview_controller.dart';
import 'in_app_webview_options.dart';
import 'in_app_webview_settings.dart';
import '../pull_to_refresh/pull_to_refresh_controller.dart';
import '../pull_to_refresh/pull_to_refresh_options.dart';
import '../util.dart';
@ -49,7 +49,8 @@ class HeadlessInAppWebView implements WebView {
this.initialUrlRequest,
this.initialFile,
this.initialData,
this.initialOptions,
@Deprecated('Use initialSettings instead') this.initialOptions,
this.initialSettings,
this.contextMenu,
this.initialUserScripts,
this.pullToRefreshController,
@ -64,7 +65,7 @@ class HeadlessInAppWebView implements WebView {
this.shouldOverrideUrlLoading,
this.onLoadResource,
this.onScrollChanged,
@Deprecated('Use `onDownloadStartRequest` instead')
@Deprecated('Use onDownloadStartRequest instead')
this.onDownloadStart,
this.onDownloadStartRequest,
this.onLoadResourceCustomScheme,
@ -91,25 +92,41 @@ class HeadlessInAppWebView implements WebView {
this.onWindowFocus,
this.onWindowBlur,
this.onOverScrolled,
this.androidOnSafeBrowsingHit,
this.androidOnPermissionRequest,
this.androidOnGeolocationPermissionsShowPrompt,
this.androidOnGeolocationPermissionsHidePrompt,
this.androidShouldInterceptRequest,
this.androidOnRenderProcessGone,
this.androidOnRenderProcessResponsive,
this.androidOnRenderProcessUnresponsive,
this.androidOnFormResubmission,
@Deprecated('Use `onZoomScaleChanged` instead')
this.androidOnScaleChanged,
this.androidOnReceivedIcon,
this.androidOnReceivedTouchIconUrl,
this.androidOnJsBeforeUnload,
this.androidOnReceivedLoginRequest,
this.iosOnWebContentProcessDidTerminate,
this.iosOnDidReceiveServerRedirectForProvisionalNavigation,
this.iosOnNavigationResponse,
this.iosShouldAllowDeprecatedTLS}) {
@Deprecated('Use onSafeBrowsingHit instead') this.androidOnSafeBrowsingHit,
this.onSafeBrowsingHit,
@Deprecated('Use onPermissionRequest instead') this.androidOnPermissionRequest,
this.onPermissionRequest,
@Deprecated('Use onGeolocationPermissionsShowPrompt instead') this.androidOnGeolocationPermissionsShowPrompt,
this.onGeolocationPermissionsShowPrompt,
@Deprecated('Use onGeolocationPermissionsHidePrompt instead') this.androidOnGeolocationPermissionsHidePrompt,
this.onGeolocationPermissionsHidePrompt,
@Deprecated('Use shouldInterceptRequest instead') this.androidShouldInterceptRequest,
this.shouldInterceptRequest,
@Deprecated('Use onRenderProcessGone instead') this.androidOnRenderProcessGone,
this.onRenderProcessGone,
@Deprecated('Use onRenderProcessResponsive instead') this.androidOnRenderProcessResponsive,
this.onRenderProcessResponsive,
@Deprecated('Use onRenderProcessUnresponsive instead') this.androidOnRenderProcessUnresponsive,
this.onRenderProcessUnresponsive,
@Deprecated('Use onFormResubmission instead') this.androidOnFormResubmission,
this.onFormResubmission,
@Deprecated('Use onZoomScaleChanged instead') this.androidOnScaleChanged,
@Deprecated('Use onReceivedIcon instead') this.androidOnReceivedIcon,
this.onReceivedIcon,
@Deprecated('Use onReceivedTouchIconUrl instead') this.androidOnReceivedTouchIconUrl,
this.onReceivedTouchIconUrl,
@Deprecated('Use onJsBeforeUnload instead') this.androidOnJsBeforeUnload,
this.onJsBeforeUnload,
@Deprecated('Use onReceivedLoginRequest instead') this.androidOnReceivedLoginRequest,
this.onReceivedLoginRequest,
@Deprecated('Use onWebContentProcessDidTerminate instead') this.iosOnWebContentProcessDidTerminate,
this.onWebContentProcessDidTerminate,
@Deprecated('Use onDidReceiveServerRedirectForProvisionalNavigation instead') this.iosOnDidReceiveServerRedirectForProvisionalNavigation,
this.onDidReceiveServerRedirectForProvisionalNavigation,
@Deprecated('Use onNavigationResponse instead') this.iosOnNavigationResponse,
this.onNavigationResponse,
@Deprecated('Use shouldAllowDeprecatedTLS instead') this.iosShouldAllowDeprecatedTLS,
this.shouldAllowDeprecatedTLS,}) {
id = IdGenerator.generate();
webViewController = new InAppWebViewController(id, this);
this._channel =
@ -137,6 +154,12 @@ class HeadlessInAppWebView implements WebView {
return;
}
_started = true;
Map<String, dynamic> initialSettings = (this.initialSettings != null ?
this.initialSettings?.toMap() :
// ignore: deprecated_member_use_from_same_package
this.initialOptions?.toMap()) ?? {};
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('id', () => id);
args.putIfAbsent(
@ -145,7 +168,7 @@ class HeadlessInAppWebView implements WebView {
'initialUrlRequest': this.initialUrlRequest?.toMap(),
'initialFile': this.initialFile,
'initialData': this.initialData?.toMap(),
'initialOptions': this.initialOptions?.toMap() ?? {},
'initialSettings': initialSettings,
'contextMenu': this.contextMenu?.toMap() ?? {},
'windowId': this.windowId,
'implementation': this.implementation.toValue(),
@ -215,8 +238,12 @@ class HeadlessInAppWebView implements WebView {
final String? initialFile;
@override
@Deprecated('Use initialSettings instead')
final InAppWebViewGroupOptions? initialOptions;
@override
final InAppWebViewSettings? initialSettings;
@override
final ContextMenu? contextMenu;
@ -232,20 +259,28 @@ class HeadlessInAppWebView implements WebView {
@override
final WebViewImplementation implementation;
///Use [onGeolocationPermissionsHidePrompt] instead.
@override
@Deprecated('Use onGeolocationPermissionsHidePrompt instead')
void Function(InAppWebViewController controller)?
androidOnGeolocationPermissionsHidePrompt;
///Use [onGeolocationPermissionsShowPrompt] instead.
@override
@Deprecated('Use onGeolocationPermissionsShowPrompt instead')
Future<GeolocationPermissionShowPromptResponse?> Function(
InAppWebViewController controller, String origin)?
androidOnGeolocationPermissionsShowPrompt;
///Use [onPermissionRequest] instead.
@override
@Deprecated('Use onPermissionRequest instead')
Future<PermissionRequestResponse?> Function(InAppWebViewController controller,
String origin, List<String> resources)? androidOnPermissionRequest;
///Use [onSafeBrowsingHit] instead.
@override
@Deprecated('Use onSafeBrowsingHit instead')
Future<SafeBrowsingResponse?> Function(InAppWebViewController controller,
Uri url, SafeBrowsingThreat? threatType)? androidOnSafeBrowsingHit;
@ -257,20 +292,28 @@ class HeadlessInAppWebView implements WebView {
void Function(InAppWebViewController controller, String? title)?
onTitleChanged;
///Use [onDidReceiveServerRedirectForProvisionalNavigation] instead.
@override
@Deprecated('Use onDidReceiveServerRedirectForProvisionalNavigation instead')
void Function(InAppWebViewController controller)?
iosOnDidReceiveServerRedirectForProvisionalNavigation;
///Use [onWebContentProcessDidTerminate] instead.
@override
@Deprecated('Use onWebContentProcessDidTerminate instead')
void Function(InAppWebViewController controller)?
iosOnWebContentProcessDidTerminate;
///Use [onNavigationResponse] instead.
@override
@Deprecated('Use onNavigationResponse instead')
Future<IOSNavigationResponseAction?> Function(
InAppWebViewController controller,
IOSWKNavigationResponse navigationResponse)? iosOnNavigationResponse;
///Use [shouldAllowDeprecatedTLS] instead.
@override
@Deprecated('Use shouldAllowDeprecatedTLS instead')
Future<IOSShouldAllowDeprecatedTLSAction?> Function(
InAppWebViewController controller,
URLAuthenticationChallenge challenge)? iosShouldAllowDeprecatedTLS;
@ -304,7 +347,7 @@ class HeadlessInAppWebView implements WebView {
void Function(InAppWebViewController controller)? onWindowBlur;
///Use [onDownloadStartRequest] instead
@Deprecated('Use `onDownloadStartRequest` instead')
@Deprecated('Use onDownloadStartRequest instead')
@override
final void Function(InAppWebViewController controller, Uri url)?
onDownloadStart;
@ -383,7 +426,7 @@ class HeadlessInAppWebView implements WebView {
@override
void Function(
InAppWebViewController controller, Uri? url, bool? androidIsReload)?
InAppWebViewController controller, Uri? url, bool? isReload)?
onUpdateVisitedHistory;
@override
@ -419,50 +462,119 @@ class HeadlessInAppWebView implements WebView {
InAppWebViewController controller, double oldScale, double newScale)?
onZoomScaleChanged;
///Use [shouldInterceptRequest] instead.
@override
@Deprecated('Use shouldInterceptRequest instead')
Future<WebResourceResponse?> Function(
InAppWebViewController controller, WebResourceRequest request)?
androidShouldInterceptRequest;
///Use [onRenderProcessUnresponsive] instead.
@override
@Deprecated('Use onRenderProcessUnresponsive instead')
Future<WebViewRenderProcessAction?> Function(
InAppWebViewController controller, Uri? url)?
androidOnRenderProcessUnresponsive;
///Use [onRenderProcessResponsive] instead.
@override
@Deprecated('Use onRenderProcessResponsive instead')
Future<WebViewRenderProcessAction?> Function(
InAppWebViewController controller, Uri? url)?
androidOnRenderProcessResponsive;
///Use [onRenderProcessGone] instead.
@override
@Deprecated('Use onRenderProcessGone instead')
void Function(
InAppWebViewController controller, RenderProcessGoneDetail detail)?
androidOnRenderProcessGone;
///Use [onFormResubmission] instead.
@override
@Deprecated('Use onFormResubmission instead')
Future<FormResubmissionAction?> Function(
InAppWebViewController controller, Uri? url)? androidOnFormResubmission;
///Use [onZoomScaleChanged] instead.
@Deprecated('Use `onZoomScaleChanged` instead')
@Deprecated('Use onZoomScaleChanged instead')
@override
void Function(
InAppWebViewController controller, double oldScale, double newScale)?
androidOnScaleChanged;
///Use [onReceivedIcon] instead
@override
@Deprecated('Use onReceivedIcon instead')
void Function(InAppWebViewController controller, Uint8List icon)?
androidOnReceivedIcon;
///Use [onReceivedTouchIconUrl] instead
@override
@Deprecated('Use onReceivedTouchIconUrl instead')
void Function(InAppWebViewController controller, Uri url, bool precomposed)?
androidOnReceivedTouchIconUrl;
///Use [onJsBeforeUnload] instead.
@override
@Deprecated('Use onJsBeforeUnload instead')
Future<JsBeforeUnloadResponse?> Function(InAppWebViewController controller,
JsBeforeUnloadRequest jsBeforeUnloadRequest)? androidOnJsBeforeUnload;
///Use [onReceivedLoginRequest] instead.
@override
@Deprecated('Use onReceivedLoginRequest instead')
void Function(InAppWebViewController controller, LoginRequest loginRequest)?
androidOnReceivedLoginRequest;
@override
void Function(InAppWebViewController controller)? onDidReceiveServerRedirectForProvisionalNavigation;
@override
Future<FormResubmissionAction?> Function(InAppWebViewController controller, Uri? url)? onFormResubmission;
@override
void Function(InAppWebViewController controller)? onGeolocationPermissionsHidePrompt;
@override
Future<GeolocationPermissionShowPromptResponse?> Function(InAppWebViewController controller, String origin)? onGeolocationPermissionsShowPrompt;
@override
Future<JsBeforeUnloadResponse?> Function(InAppWebViewController controller, JsBeforeUnloadRequest jsBeforeUnloadRequest)? onJsBeforeUnload;
@override
Future<NavigationResponseAction?> Function(InAppWebViewController controller, NavigationResponse navigationResponse)? onNavigationResponse;
@override
Future<PermissionRequestResponse?> Function(InAppWebViewController controller, String origin, List<String> resources)? onPermissionRequest;
@override
void Function(InAppWebViewController controller, Uint8List icon)? onReceivedIcon;
@override
void Function(InAppWebViewController controller, LoginRequest loginRequest)? onReceivedLoginRequest;
@override
void Function(InAppWebViewController controller, Uri url, bool precomposed)? onReceivedTouchIconUrl;
@override
void Function(InAppWebViewController controller, RenderProcessGoneDetail detail)? onRenderProcessGone;
@override
Future<WebViewRenderProcessAction?> Function(InAppWebViewController controller, Uri? url)? onRenderProcessResponsive;
@override
Future<WebViewRenderProcessAction?> Function(InAppWebViewController controller, Uri? url)? onRenderProcessUnresponsive;
@override
Future<SafeBrowsingResponse?> Function(InAppWebViewController controller, Uri url, SafeBrowsingThreat? threatType)? onSafeBrowsingHit;
@override
void Function(InAppWebViewController controller)? onWebContentProcessDidTerminate;
@override
Future<ShouldAllowDeprecatedTLSAction?> Function(InAppWebViewController controller, URLAuthenticationChallenge challenge)? shouldAllowDeprecatedTLS;
@override
Future<WebResourceResponse?> Function(InAppWebViewController controller, WebResourceRequest request)? shouldInterceptRequest;
}

View File

@ -8,15 +8,14 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import '../context_menu.dart';
import '../types.dart';
import 'webview.dart';
import 'in_app_webview_controller.dart';
import 'in_app_webview_options.dart';
import '../pull_to_refresh/pull_to_refresh_controller.dart';
import 'in_app_webview_settings.dart';
import '../pull_to_refresh/main.dart';
///Flutter Widget for adding an **inline native WebView** integrated in the flutter widget tree.
class InAppWebView extends StatefulWidget implements WebView {
@ -38,7 +37,8 @@ class InAppWebView extends StatefulWidget implements WebView {
this.initialUrlRequest,
this.initialFile,
this.initialData,
this.initialOptions,
@Deprecated('Use initialSettings instead') this.initialOptions,
this.initialSettings,
this.initialUserScripts,
this.pullToRefreshController,
this.implementation = WebViewImplementation.NATIVE,
@ -53,7 +53,7 @@ class InAppWebView extends StatefulWidget implements WebView {
this.shouldOverrideUrlLoading,
this.onLoadResource,
this.onScrollChanged,
@Deprecated('Use `onDownloadStartRequest` instead') this.onDownloadStart,
@Deprecated('Use onDownloadStartRequest instead') this.onDownloadStart,
this.onDownloadStartRequest,
this.onLoadResourceCustomScheme,
this.onCreateWindow,
@ -80,46 +80,71 @@ class InAppWebView extends StatefulWidget implements WebView {
this.onWindowBlur,
this.onOverScrolled,
this.onZoomScaleChanged,
this.androidOnSafeBrowsingHit,
this.androidOnPermissionRequest,
this.androidOnGeolocationPermissionsShowPrompt,
this.androidOnGeolocationPermissionsHidePrompt,
this.androidShouldInterceptRequest,
this.androidOnRenderProcessGone,
this.androidOnRenderProcessResponsive,
this.androidOnRenderProcessUnresponsive,
this.androidOnFormResubmission,
@Deprecated('Use `onZoomScaleChanged` instead') this.androidOnScaleChanged,
this.androidOnReceivedIcon,
this.androidOnReceivedTouchIconUrl,
this.androidOnJsBeforeUnload,
this.androidOnReceivedLoginRequest,
this.iosOnWebContentProcessDidTerminate,
this.iosOnDidReceiveServerRedirectForProvisionalNavigation,
this.iosOnNavigationResponse,
this.iosShouldAllowDeprecatedTLS,
@Deprecated('Use onSafeBrowsingHit instead') this.androidOnSafeBrowsingHit,
this.onSafeBrowsingHit,
@Deprecated('Use onPermissionRequest instead') this.androidOnPermissionRequest,
this.onPermissionRequest,
@Deprecated('Use onGeolocationPermissionsShowPrompt instead') this.androidOnGeolocationPermissionsShowPrompt,
this.onGeolocationPermissionsShowPrompt,
@Deprecated('Use onGeolocationPermissionsHidePrompt instead') this.androidOnGeolocationPermissionsHidePrompt,
this.onGeolocationPermissionsHidePrompt,
@Deprecated('Use shouldInterceptRequest instead') this.androidShouldInterceptRequest,
this.shouldInterceptRequest,
@Deprecated('Use onRenderProcessGone instead') this.androidOnRenderProcessGone,
this.onRenderProcessGone,
@Deprecated('Use onRenderProcessResponsive instead') this.androidOnRenderProcessResponsive,
this.onRenderProcessResponsive,
@Deprecated('Use onRenderProcessUnresponsive instead') this.androidOnRenderProcessUnresponsive,
this.onRenderProcessUnresponsive,
@Deprecated('Use onFormResubmission instead') this.androidOnFormResubmission,
this.onFormResubmission,
@Deprecated('Use onZoomScaleChanged instead') this.androidOnScaleChanged,
@Deprecated('Use onReceivedIcon instead') this.androidOnReceivedIcon,
this.onReceivedIcon,
@Deprecated('Use onReceivedTouchIconUrl instead') this.androidOnReceivedTouchIconUrl,
this.onReceivedTouchIconUrl,
@Deprecated('Use onJsBeforeUnload instead') this.androidOnJsBeforeUnload,
this.onJsBeforeUnload,
@Deprecated('Use onReceivedLoginRequest instead') this.androidOnReceivedLoginRequest,
this.onReceivedLoginRequest,
@Deprecated('Use onWebContentProcessDidTerminate instead') this.iosOnWebContentProcessDidTerminate,
this.onWebContentProcessDidTerminate,
@Deprecated('Use onDidReceiveServerRedirectForProvisionalNavigation instead') this.iosOnDidReceiveServerRedirectForProvisionalNavigation,
this.onDidReceiveServerRedirectForProvisionalNavigation,
@Deprecated('Use onNavigationResponse instead') this.iosOnNavigationResponse,
this.onNavigationResponse,
@Deprecated('Use shouldAllowDeprecatedTLS instead') this.iosShouldAllowDeprecatedTLS,
this.shouldAllowDeprecatedTLS,
this.gestureRecognizers,
}) : super(key: key);
@override
_InAppWebViewState createState() => _InAppWebViewState();
///Use [onGeolocationPermissionsHidePrompt] instead.
@override
@Deprecated('Use onGeolocationPermissionsHidePrompt instead')
final void Function(InAppWebViewController controller)?
androidOnGeolocationPermissionsHidePrompt;
///Use [onGeolocationPermissionsShowPrompt] instead.
@override
@Deprecated('Use onGeolocationPermissionsShowPrompt instead')
final Future<GeolocationPermissionShowPromptResponse?> Function(
InAppWebViewController controller, String origin)?
androidOnGeolocationPermissionsShowPrompt;
///Use [onPermissionRequest] instead.
@override
@Deprecated('Use onPermissionRequest instead')
final Future<PermissionRequestResponse?> Function(
InAppWebViewController controller,
String origin,
List<String> resources)? androidOnPermissionRequest;
///Use [onSafeBrowsingHit] instead.
@override
@Deprecated('Use onSafeBrowsingHit instead')
final Future<SafeBrowsingResponse?> Function(
InAppWebViewController controller,
Uri url,
@ -131,9 +156,14 @@ class InAppWebView extends StatefulWidget implements WebView {
@override
final String? initialFile;
///Use [initialSettings] instead.
@override
@Deprecated('Use initialSettings instead')
final InAppWebViewGroupOptions? initialOptions;
@override
final InAppWebViewSettings? initialSettings;
@override
final URLRequest? initialUrlRequest;
@ -157,20 +187,28 @@ class InAppWebView extends StatefulWidget implements WebView {
final void Function(InAppWebViewController controller, String? title)?
onTitleChanged;
///Use [onDidReceiveServerRedirectForProvisionalNavigation] instead.
@override
@Deprecated('Use onDidReceiveServerRedirectForProvisionalNavigation instead')
final void Function(InAppWebViewController controller)?
iosOnDidReceiveServerRedirectForProvisionalNavigation;
///Use [onWebContentProcessDidTerminate] instead.
@override
@Deprecated('Use onWebContentProcessDidTerminate instead')
final void Function(InAppWebViewController controller)?
iosOnWebContentProcessDidTerminate;
///Use [onNavigationResponse] instead.
@override
@Deprecated('Use onNavigationResponse instead')
final Future<IOSNavigationResponseAction?> Function(
InAppWebViewController controller,
IOSWKNavigationResponse navigationResponse)? iosOnNavigationResponse;
///Use [shouldAllowDeprecatedTLS] instead.
@override
@Deprecated('Use shouldAllowDeprecatedTLS instead')
final Future<IOSShouldAllowDeprecatedTLSAction?> Function(
InAppWebViewController controller,
URLAuthenticationChallenge challenge)? iosShouldAllowDeprecatedTLS;
@ -203,17 +241,21 @@ class InAppWebView extends StatefulWidget implements WebView {
@override
final void Function(InAppWebViewController controller)? onWindowBlur;
///Use [onReceivedIcon] instead
@override
@Deprecated('Use onReceivedIcon instead')
final void Function(InAppWebViewController controller, Uint8List icon)?
androidOnReceivedIcon;
///Use [onReceivedTouchIconUrl] instead
@override
@Deprecated('Use onReceivedTouchIconUrl instead')
final void Function(
InAppWebViewController controller, Uri url, bool precomposed)?
androidOnReceivedTouchIconUrl;
///Use [onDownloadStartRequest] instead
@Deprecated('Use `onDownloadStartRequest` instead')
@Deprecated('Use onDownloadStartRequest instead')
@override
final void Function(InAppWebViewController controller, Uri url)?
onDownloadStart;
@ -294,7 +336,7 @@ class InAppWebView extends StatefulWidget implements WebView {
@override
final void Function(
InAppWebViewController controller, Uri? url, bool? androidIsReload)?
InAppWebViewController controller, Uri? url, bool? isReload)?
onUpdateVisitedHistory;
@override
@ -330,46 +372,111 @@ class InAppWebView extends StatefulWidget implements WebView {
InAppWebViewController controller, double oldScale, double newScale)?
onZoomScaleChanged;
///Use [shouldInterceptRequest] instead.
@override
@Deprecated('Use shouldInterceptRequest instead')
final Future<WebResourceResponse?> Function(
InAppWebViewController controller, WebResourceRequest request)?
androidShouldInterceptRequest;
///Use [onRenderProcessUnresponsive] instead.
@override
@Deprecated('Use onRenderProcessUnresponsive instead')
final Future<WebViewRenderProcessAction?> Function(
InAppWebViewController controller, Uri? url)?
androidOnRenderProcessUnresponsive;
///Use [onRenderProcessResponsive] instead.
@override
@Deprecated('Use onRenderProcessResponsive instead')
final Future<WebViewRenderProcessAction?> Function(
InAppWebViewController controller, Uri? url)?
androidOnRenderProcessResponsive;
///Use [onRenderProcessGone] instead.
@override
@Deprecated('Use onRenderProcessGone instead')
final void Function(
InAppWebViewController controller, RenderProcessGoneDetail detail)?
androidOnRenderProcessGone;
///Use [onFormResubmission] instead.
@override
@Deprecated('Use onFormResubmission instead')
final Future<FormResubmissionAction?> Function(
InAppWebViewController controller, Uri? url)? androidOnFormResubmission;
///Use [onZoomScaleChanged] instead.
@Deprecated('Use `onZoomScaleChanged` instead')
@Deprecated('Use onZoomScaleChanged instead')
@override
final void Function(
InAppWebViewController controller, double oldScale, double newScale)?
androidOnScaleChanged;
///Use [onJsBeforeUnload] instead.
@override
@Deprecated('Use onJsBeforeUnload instead')
final Future<JsBeforeUnloadResponse?> Function(
InAppWebViewController controller,
JsBeforeUnloadRequest jsBeforeUnloadRequest)? androidOnJsBeforeUnload;
///Use [onReceivedLoginRequest] instead.
@override
@Deprecated('Use onReceivedLoginRequest instead')
final void Function(
InAppWebViewController controller, LoginRequest loginRequest)?
androidOnReceivedLoginRequest;
@override
final void Function(InAppWebViewController controller)? onDidReceiveServerRedirectForProvisionalNavigation;
@override
final Future<FormResubmissionAction?> Function(InAppWebViewController controller, Uri? url)? onFormResubmission;
@override
final void Function(InAppWebViewController controller)? onGeolocationPermissionsHidePrompt;
@override
final Future<GeolocationPermissionShowPromptResponse?> Function(InAppWebViewController controller, String origin)? onGeolocationPermissionsShowPrompt;
@override
final Future<JsBeforeUnloadResponse?> Function(InAppWebViewController controller, JsBeforeUnloadRequest jsBeforeUnloadRequest)? onJsBeforeUnload;
@override
final Future<NavigationResponseAction?> Function(InAppWebViewController controller, NavigationResponse navigationResponse)? onNavigationResponse;
@override
final Future<PermissionRequestResponse?> Function(InAppWebViewController controller, String origin, List<String> resources)? onPermissionRequest;
@override
final void Function(InAppWebViewController controller, Uint8List icon)? onReceivedIcon;
@override
final void Function(InAppWebViewController controller, LoginRequest loginRequest)? onReceivedLoginRequest;
@override
final void Function(InAppWebViewController controller, Uri url, bool precomposed)? onReceivedTouchIconUrl;
@override
final void Function(InAppWebViewController controller, RenderProcessGoneDetail detail)? onRenderProcessGone;
@override
final Future<WebViewRenderProcessAction?> Function(InAppWebViewController controller, Uri? url)? onRenderProcessResponsive;
@override
final Future<WebViewRenderProcessAction?> Function(InAppWebViewController controller, Uri? url)? onRenderProcessUnresponsive;
@override
final Future<SafeBrowsingResponse?> Function(InAppWebViewController controller, Uri url, SafeBrowsingThreat? threatType)? onSafeBrowsingHit;
@override
final void Function(InAppWebViewController controller)? onWebContentProcessDidTerminate;
@override
final Future<ShouldAllowDeprecatedTLSAction?> Function(InAppWebViewController controller, URLAuthenticationChallenge challenge)? shouldAllowDeprecatedTLS;
@override
final Future<WebResourceResponse?> Function(InAppWebViewController controller, WebResourceRequest request)? shouldInterceptRequest;
}
class _InAppWebViewState extends State<InAppWebView> {
@ -377,9 +484,16 @@ class _InAppWebViewState extends State<InAppWebView> {
@override
Widget build(BuildContext context) {
Map<String, dynamic> initialSettings = (widget.initialSettings != null ?
widget.initialSettings?.toMap() :
// ignore: deprecated_member_use_from_same_package
widget.initialOptions?.toMap()) ?? {};
if (defaultTargetPlatform == TargetPlatform.android) {
var useHybridComposition =
widget.initialOptions?.android.useHybridComposition ?? false;
var useHybridComposition = (widget.initialSettings != null ?
widget.initialSettings?.useHybridComposition :
// ignore: deprecated_member_use_from_same_package
widget.initialOptions?.android.useHybridComposition) ?? false;
if (!useHybridComposition && widget.pullToRefreshController != null) {
throw new Exception(
@ -409,7 +523,7 @@ class _InAppWebViewState extends State<InAppWebView> {
'initialUrlRequest': widget.initialUrlRequest?.toMap(),
'initialFile': widget.initialFile,
'initialData': widget.initialData?.toMap(),
'initialOptions': widget.initialOptions?.toMap() ?? {},
'initialSettings': initialSettings,
'contextMenu': widget.contextMenu?.toMap() ?? {},
'windowId': widget.windowId,
'implementation': widget.implementation.toValue(),
@ -438,7 +552,7 @@ class _InAppWebViewState extends State<InAppWebView> {
'initialUrlRequest': widget.initialUrlRequest?.toMap(),
'initialFile': widget.initialFile,
'initialData': widget.initialData?.toMap(),
'initialOptions': widget.initialOptions?.toMap() ?? {},
'initialSettings': initialSettings,
'contextMenu': widget.contextMenu?.toMap() ?? {},
'windowId': widget.windowId,
'implementation': widget.implementation.toValue(),
@ -460,7 +574,7 @@ class _InAppWebViewState extends State<InAppWebView> {
'initialUrlRequest': widget.initialUrlRequest?.toMap(),
'initialFile': widget.initialFile,
'initialData': widget.initialData?.toMap(),
'initialOptions': widget.initialOptions?.toMap() ?? {},
'initialSettings': initialSettings,
'contextMenu': widget.contextMenu?.toMap() ?? {},
'windowId': widget.windowId,
'implementation': widget.implementation.toValue(),

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,25 +1,19 @@
import 'dart:async';
import 'dart:core';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import '../_static_channel.dart';
import '../../types.dart';
import '../in_app_webview_controller.dart';
///Class represents the iOS controller that contains only iOS-specific methods for the WebView.
class IOSInAppWebViewController {
///Class mixin that contains only iOS-specific methods for the WebView.
abstract class IOSInAppWebViewControllerMixin {
late MethodChannel _channel;
static MethodChannel _staticChannel = IN_APP_WEBVIEW_STATIC_CHANNEL;
IOSInAppWebViewController({required MethodChannel channel}) {
this._channel = channel;
}
///Reloads the current page, performing end-to-end revalidation using cache-validating conditionals if possible.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1414956-reloadfromorigin
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKWebView.reloadFromOrigin](https://developer.apple.com/documentation/webkit/wkwebview/1414956-reloadfromorigin))
Future<void> reloadFromOrigin() async {
Map<String, dynamic> args = <String, dynamic>{};
await _channel.invokeMethod('reloadFromOrigin', args);
@ -28,16 +22,19 @@ class IOSInAppWebViewController {
///Generates PDF data from the web views contents asynchronously.
///Returns `null` if a problem occurred.
///
///[iosWKPdfConfiguration] represents the object that specifies the portion of the web view to capture as PDF data.
///[pdfConfiguration] represents the object that specifies the portion of the web view to capture as PDF data.
///
///**NOTE**: available only on iOS 14.0+.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/3650490-createpdf
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKWebView.createPdf](https://developer.apple.com/documentation/webkit/wkwebview/3650490-createpdf))
Future<Uint8List?> createPdf(
{IOSWKPDFConfiguration? iosWKPdfConfiguration}) async {
// ignore: deprecated_member_use_from_same_package
{@Deprecated("Use pdfConfiguration instead") IOSWKPDFConfiguration? iosWKPdfConfiguration,
PDFConfiguration? pdfConfiguration}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent(
'iosWKPdfConfiguration', () => iosWKPdfConfiguration?.toMap());
'pdfConfiguration', () => pdfConfiguration?.toMap() ?? iosWKPdfConfiguration?.toMap());
return await _channel.invokeMethod('createPdf', args);
}
@ -46,7 +43,8 @@ class IOSInAppWebViewController {
///
///**NOTE**: available only on iOS 14.0+.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/3650491-createwebarchivedata
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKWebView.createWebArchiveData](https://developer.apple.com/documentation/webkit/wkwebview/3650491-createwebarchivedata))
Future<Uint8List?> createWebArchiveData() async {
Map<String, dynamic> args = <String, dynamic>{};
return await _channel.invokeMethod('createWebArchiveData', args);
@ -54,22 +52,25 @@ class IOSInAppWebViewController {
///A Boolean value indicating whether all resources on the page have been loaded over securely encrypted connections.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/1415002-hasonlysecurecontent
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKWebView.hasOnlySecureContent](https://developer.apple.com/documentation/webkit/wkwebview/1415002-hasonlysecurecontent))
Future<bool> hasOnlySecureContent() async {
Map<String, dynamic> args = <String, dynamic>{};
return await _channel.invokeMethod('hasOnlySecureContent', args);
}
}
///Returns a Boolean value that indicates whether WebKit natively supports resources with the specified URL scheme.
///
///[urlScheme] represents the URL scheme associated with the resource.
///
///**NOTE**: available only on iOS 11.0+.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkwebview/2875370-handlesurlscheme
///Use [InAppWebViewController] instead.
@Deprecated("Use InAppWebViewController instead")
class IOSInAppWebViewController with IOSInAppWebViewControllerMixin {
late MethodChannel _channel;
IOSInAppWebViewController({required MethodChannel channel}) {
this._channel = channel;
}
///Use [InAppWebViewController.handlesURLScheme] instead.
@Deprecated("Use InAppWebViewController.handlesURLScheme instead")
static Future<bool> handlesURLScheme(String urlScheme) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('urlScheme', () => urlScheme);
return await _staticChannel.invokeMethod('handlesURLScheme', args);
return await InAppWebViewController.handlesURLScheme(urlScheme);
}
}

View File

@ -1,7 +1,7 @@
export 'webview.dart';
export 'in_app_webview.dart';
export 'in_app_webview_controller.dart';
export 'in_app_webview_options.dart';
export 'in_app_webview_settings.dart';
export 'headless_in_app_webview.dart';
export 'android/main.dart';
export 'ios/main.dart';

View File

@ -7,17 +7,19 @@ import '../context_menu.dart';
import '../types.dart';
import 'in_app_webview_controller.dart';
import 'in_app_webview_options.dart';
import 'in_app_webview_settings.dart';
import 'headless_in_app_webview.dart';
import 'android/in_app_webview_options.dart';
///Abstract class that represents a WebView. Used by [InAppWebView] and [HeadlessInAppWebView].
abstract class WebView {
///The window id of a [CreateWindowAction.windowId].
final int? windowId;
///Event fired when the [WebView] is created.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
final void Function(InAppWebViewController controller)? onWebViewCreated;
///Event fired when the [WebView] starts to load an [url].
@ -36,9 +38,9 @@ abstract class WebView {
///Event fired when the [WebView] encounters an error loading an [url].
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedError(android.webkit.WebView,%20int,%20java.lang.String,%20java.lang.String)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455623-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedError](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedError(android.webkit.WebView,%20int,%20java.lang.String,%20java.lang.String)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455623-webview))
final void Function(InAppWebViewController controller, Uri? url, int code,
String message)? onLoadError;
@ -52,9 +54,9 @@ abstract class WebView {
///
///**NOTE**: available on Android 23+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedHttpError(android.webkit.WebView,%20android.webkit.WebResourceRequest,%20android.webkit.WebResourceResponse)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedHttpError](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedHttpError(android.webkit.WebView,%20android.webkit.WebResourceRequest,%20android.webkit.WebResourceResponse)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview))
final void Function(InAppWebViewController controller, Uri? url,
int statusCode, String description)? onLoadHttpError;
@ -68,7 +70,9 @@ abstract class WebView {
///Event fired when the [WebView] receives a [ConsoleMessage].
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onConsoleMessage(android.webkit.ConsoleMessage)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onConsoleMessage](https://developer.android.com/reference/android/webkit/WebChromeClient#onConsoleMessage(android.webkit.ConsoleMessage)))
///- iOS
final void Function(
InAppWebViewController controller, ConsoleMessage consoleMessage)?
onConsoleMessage;
@ -76,26 +80,30 @@ abstract class WebView {
///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.
///
///Note that on Android there isn't any way to load an URL for a frame that is not the main frame, so if the request is not for the main frame, the navigation is allowed by default.
///However, if you want to cancel requests for subframes, you can use the [AndroidInAppWebViewOptions.regexToCancelSubFramesLoading] option
///However, if you want to cancel requests for subframes, you can use the [InAppWebViewSettings.regexToCancelSubFramesLoading] option
///to write a Regular Expression that, if the url request of a subframe matches, then the request of that subframe is canceled.
///
///Also, on Android, this method is not called for POST requests.
///
///[navigationAction] represents an object that contains information about an action that causes navigation to occur.
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldOverrideUrlLoading] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldOverrideUrlLoading] option to `true`.
///Also, on Android this event is not called on the first page load.
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.shouldOverrideUrlLoading](https://developer.android.com/reference/android/webkit/WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView,%20java.lang.String)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455641-webview))
final Future<NavigationActionPolicy?> Function(
InAppWebViewController controller, NavigationAction navigationAction)?
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`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useOnLoadResource] and [InAppWebViewSettings.javaScriptEnabled] options to `true`.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
final void Function(
InAppWebViewController controller, LoadedResource resource)?
onLoadResource;
@ -106,14 +114,14 @@ abstract class WebView {
///
///[y] represents the current vertical scroll origin in pixels.
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.onScrollChanged](https://developer.android.com/reference/android/webkit/WebView#onScrollChanged(int,%20int,%20int,%20int)))
///- iOS ([Official API - UIScrollViewDelegate.scrollViewDidScroll](https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619392-scrollviewdidscroll))
final void Function(InAppWebViewController controller, int x, int y)?
onScrollChanged;
///Use [onDownloadStartRequest] instead
@Deprecated('Use `onDownloadStartRequest` instead')
@Deprecated('Use onDownloadStartRequest instead')
final void Function(InAppWebViewController controller, Uri url)?
onDownloadStart;
@ -122,11 +130,11 @@ abstract class WebView {
///
///[downloadStartRequest] represents the request of the file to download.
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useOnDownloadStart] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useOnDownloadStart] option to `true`.
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.setDownloadListener](https://developer.android.com/reference/android/webkit/WebView#setDownloadListener(android.webkit.DownloadListener)))
///- iOS
final void Function(InAppWebViewController controller,
DownloadStartRequest downloadStartRequest)? onDownloadStartRequest;
@ -134,7 +142,9 @@ abstract class WebView {
///
///[url] represents the url of the request.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkurlschemehandler
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS ([Official API - WKURLSchemeHandler](https://developer.apple.com/documentation/webkit/wkurlschemehandler))
final Future<CustomSchemeResponse?> Function(
InAppWebViewController controller, Uri url)? onLoadResourceCustomScheme;
@ -146,46 +156,54 @@ abstract class WebView {
///
///- [createWindowAction] represents the request.
///
///**NOTE**: to allow JavaScript to open windows, you need to set [InAppWebViewOptions.javaScriptCanOpenWindowsAutomatically] option to `true`.
///**NOTE**: to allow JavaScript to open windows, you need to set [InAppWebViewSettings.javaScriptCanOpenWindowsAutomatically] option to `true`.
///
///**NOTE**: on Android you need to set [AndroidInAppWebViewOptions.supportMultipleWindows] option to `true`.
///**NOTE**: on Android you need to set [InAppWebViewSettings.supportMultipleWindows] option to `true`.
///Also, if the request has been created using JavaScript (`window.open()`), then there are some limitation: check the [NavigationAction] class.
///
///**NOTE**: on iOS, setting these initial options: [InAppWebViewOptions.supportZoom], [InAppWebViewOptions.useOnLoadResource], [InAppWebViewOptions.useShouldInterceptAjaxRequest],
///[InAppWebViewOptions.useShouldInterceptFetchRequest], [InAppWebViewOptions.applicationNameForUserAgent], [InAppWebViewOptions.javaScriptCanOpenWindowsAutomatically],
///[InAppWebViewOptions.javaScriptEnabled], [InAppWebViewOptions.minimumFontSize], [InAppWebViewOptions.preferredContentMode], [InAppWebViewOptions.incognito],
///[InAppWebViewOptions.cacheEnabled], [InAppWebViewOptions.mediaPlaybackRequiresUserGesture],
///[InAppWebViewOptions.resourceCustomSchemes], [IOSInAppWebViewOptions.sharedCookiesEnabled],
///[IOSInAppWebViewOptions.enableViewportScale], [IOSInAppWebViewOptions.allowsAirPlayForMediaPlayback],
///[IOSInAppWebViewOptions.allowsPictureInPictureMediaPlayback], [IOSInAppWebViewOptions.isFraudulentWebsiteWarningEnabled],
///[IOSInAppWebViewOptions.allowsInlineMediaPlayback], [IOSInAppWebViewOptions.suppressesIncrementalRendering], [IOSInAppWebViewOptions.selectionGranularity],
///[IOSInAppWebViewOptions.ignoresViewportScaleLimits], [IOSInAppWebViewOptions.limitsNavigationsToAppBoundDomains],
///**NOTE**: on iOS, setting these initial options: [InAppWebViewSettings.supportZoom], [InAppWebViewSettings.useOnLoadResource], [InAppWebViewSettings.useShouldInterceptAjaxRequest],
///[InAppWebViewSettings.useShouldInterceptFetchRequest], [InAppWebViewSettings.applicationNameForUserAgent], [InAppWebViewSettings.javaScriptCanOpenWindowsAutomatically],
///[InAppWebViewSettings.javaScriptEnabled], [InAppWebViewSettings.minimumFontSize], [InAppWebViewSettings.preferredContentMode], [InAppWebViewSettings.incognito],
///[InAppWebViewSettings.cacheEnabled], [InAppWebViewSettings.mediaPlaybackRequiresUserGesture],
///[InAppWebViewSettings.resourceCustomSchemes], [InAppWebViewSettings.sharedCookiesEnabled],
///[InAppWebViewSettings.enableViewportScale], [InAppWebViewSettings.allowsAirPlayForMediaPlayback],
///[InAppWebViewSettings.allowsPictureInPictureMediaPlayback], [InAppWebViewSettings.isFraudulentWebsiteWarningEnabled],
///[InAppWebViewSettings.allowsInlineMediaPlayback], [InAppWebViewSettings.suppressesIncrementalRendering], [InAppWebViewSettings.selectionGranularity],
///[InAppWebViewSettings.ignoresViewportScaleLimits], [InAppWebViewSettings.limitsNavigationsToAppBoundDomains],
///will have no effect due to a `WKWebView` limitation when creating the new window WebView: it's impossible to return the new `WKWebView`
///with a different `WKWebViewConfiguration` instance (see https://developer.apple.com/documentation/webkit/wkuidelegate/1536907-webview).
///So, these options will be inherited from the caller WebView.
///Also, note that calling [InAppWebViewController.setOptions] method using the controller of the new created WebView,
///Also, note that calling [InAppWebViewController.setSettings] method using the controller of the new created WebView,
///it will update also the WebView options of the caller WebView.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onCreateWindow(android.webkit.WebView,%20boolean,%20boolean,%20android.os.Message)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1536907-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onCreateWindow](https://developer.android.com/reference/android/webkit/WebChromeClient#onCreateWindow(android.webkit.WebView,%20boolean,%20boolean,%20android.os.Message)))
///- iOS ([Official API - WKUIDelegate.webView](https://developer.apple.com/documentation/webkit/wkuidelegate/1536907-webview))
final Future<bool?> Function(InAppWebViewController controller,
CreateWindowAction createWindowAction)? onCreateWindow;
///Event fired when the host application should close the given WebView and remove it from the view system if necessary.
///At this point, WebCore has stopped any loading in this window and has removed any cross-scripting ability in javascript.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onCloseWindow(android.webkit.WebView)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1537390-webviewdidclose
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onCloseWindow](https://developer.android.com/reference/android/webkit/WebChromeClient#onCloseWindow(android.webkit.WebView)))
///- iOS ([Official API - WKUIDelegate.webViewDidClose](https://developer.apple.com/documentation/webkit/wkuidelegate/1537390-webviewdidclose))
final void Function(InAppWebViewController controller)? onCloseWindow;
///Event fired when the JavaScript `window` object of the WebView has received focus.
///This is the result of the `focus` JavaScript event applied to the `window` object.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
final void Function(InAppWebViewController controller)? onWindowFocus;
///Event fired when the JavaScript `window` object of the WebView has lost focus.
///This is the result of the `blur` JavaScript event applied to the `window` object.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
final void Function(InAppWebViewController controller)? onWindowBlur;
///Event fired when javascript calls the `alert()` method to display an alert dialog.
@ -193,9 +211,9 @@ abstract class WebView {
///
///[jsAlertRequest] contains the message to be displayed in the alert dialog and the of the page requesting the dialog.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onJsAlert(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1537406-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onJsAlert](https://developer.android.com/reference/android/webkit/WebChromeClient#onJsAlert(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)))
///- iOS ([Official API - WKUIDelegate.webView](https://developer.apple.com/documentation/webkit/wkuidelegate/1537406-webview))
final Future<JsAlertResponse?> Function(
InAppWebViewController controller, JsAlertRequest jsAlertRequest)?
onJsAlert;
@ -205,9 +223,9 @@ abstract class WebView {
///
///[jsConfirmRequest] contains the message to be displayed in the confirm dialog and the of the page requesting the dialog.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onJsConfirm(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1536489-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onJsConfirm](https://developer.android.com/reference/android/webkit/WebChromeClient#onJsConfirm(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)))
///- iOS ([Official API - WKUIDelegate.webView](https://developer.apple.com/documentation/webkit/wkuidelegate/1536489-webview))
final Future<JsConfirmResponse?> Function(
InAppWebViewController controller, JsConfirmRequest jsConfirmRequest)?
onJsConfirm;
@ -217,9 +235,9 @@ abstract class WebView {
///
///[jsPromptRequest] contains the message to be displayed in the prompt dialog, the default value displayed in the prompt dialog, and the of the page requesting the dialog.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onJsPrompt(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20android.webkit.JsPromptResult)
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wkuidelegate/1538086-webview
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onJsPrompt](https://developer.android.com/reference/android/webkit/WebChromeClient#onJsPrompt(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20java.lang.String,%20android.webkit.JsPromptResult)))
///- iOS ([Official API - WKUIDelegate.webView](https://developer.apple.com/documentation/webkit/wkuidelegate/1538086-webview))
final Future<JsPromptResponse?> Function(
InAppWebViewController controller, JsPromptRequest jsPromptRequest)?
onJsPrompt;
@ -228,9 +246,9 @@ abstract class WebView {
///
///[challenge] contains data about host, port, protocol, realm, etc. as specified in the [URLAuthenticationChallenge].
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedHttpAuthRequest](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedHttpAuthRequest(android.webkit.WebView,%20android.webkit.HttpAuthHandler,%20java.lang.String,%20java.lang.String)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview))
final Future<HttpAuthResponse?> Function(InAppWebViewController controller,
HttpAuthenticationChallenge challenge)? onReceivedHttpAuthRequest;
@ -239,9 +257,9 @@ abstract class WebView {
///
///[challenge] contains data about host, port, protocol, realm, etc. as specified in the [ServerTrustChallenge].
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedSslError](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedSslError(android.webkit.WebView,%20android.webkit.SslErrorHandler,%20android.net.http.SslError)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview))
final Future<ServerTrustAuthResponse?> Function(
InAppWebViewController controller, ServerTrustChallenge challenge)?
onReceivedServerTrustAuthRequest;
@ -253,9 +271,9 @@ abstract class WebView {
///
///[challenge] contains data about host, port, protocol, realm, etc. as specified in the [ClientCertChallenge].
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedClientCertRequest](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedClientCertRequest(android.webkit.WebView,%20android.webkit.ClientCertRequest)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview))
final Future<ClientCertResponse?> Function(
InAppWebViewController controller, ClientCertChallenge challenge)?
onReceivedClientCertRequest;
@ -280,11 +298,15 @@ abstract class WebView {
///
///[ajaxRequest] represents the `XMLHttpRequest`.
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldInterceptAjaxRequest] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptAjaxRequest] option to `true`.
///Also, unlike iOS that has [WKUserScript](https://developer.apple.com/documentation/webkit/wkuserscript) that
///can inject javascript code right after the document element is created but before any other content is loaded, in Android the javascript code
///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.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
final Future<AjaxRequest?> Function(
InAppWebViewController controller, AjaxRequest ajaxRequest)?
shouldInterceptAjaxRequest;
@ -294,11 +316,15 @@ abstract class WebView {
///
///[ajaxRequest] represents the [XMLHttpRequest].
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldInterceptAjaxRequest] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptAjaxRequest] option to `true`.
///Also, unlike iOS that has [WKUserScript](https://developer.apple.com/documentation/webkit/wkuserscript) that
///can inject javascript code right after the document element is created but before any other content is loaded, in Android the javascript code
///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.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
final Future<AjaxRequestAction?> Function(
InAppWebViewController controller, AjaxRequest ajaxRequest)?
onAjaxReadyStateChange;
@ -308,11 +334,15 @@ abstract class WebView {
///
///[ajaxRequest] represents the [XMLHttpRequest].
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldInterceptAjaxRequest] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptAjaxRequest] option to `true`.
///Also, unlike iOS that has [WKUserScript](https://developer.apple.com/documentation/webkit/wkuserscript) that
///can inject javascript code right after the document element is created but before any other content is loaded, in Android the javascript code
///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.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
final Future<AjaxRequestAction?> Function(
InAppWebViewController controller, AjaxRequest ajaxRequest)?
onAjaxProgress;
@ -322,11 +352,15 @@ abstract class WebView {
///
///[fetchRequest] represents a resource request.
///
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewOptions.useShouldInterceptFetchRequest] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptFetchRequest] option to `true`.
///Also, unlike iOS that has [WKUserScript](https://developer.apple.com/documentation/webkit/wkuserscript) that
///can inject javascript code right after the document element is created but before any other content is loaded, in Android the javascript code
///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.
///
///**Supported Platforms/Implementations**:
///- Android native WebView
///- iOS
final Future<FetchRequest?> Function(
InAppWebViewController controller, FetchRequest fetchRequest)?
shouldInterceptFetchRequest;
@ -338,11 +372,13 @@ abstract class WebView {
///
///[url] represents the url being visited.
///
///[androidIsReload] indicates if this url is being reloaded. Available only on Android.
///[isReload] indicates if this url is being reloaded. Available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#doUpdateVisitedHistory(android.webkit.WebView,%20java.lang.String,%20boolean)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.doUpdateVisitedHistory](https://developer.android.com/reference/android/webkit/WebViewClient#doUpdateVisitedHistory(android.webkit.WebView,%20java.lang.String,%20boolean)))
///- iOS
final void Function(
InAppWebViewController controller, Uri? url, bool? androidIsReload)?
InAppWebViewController controller, Uri? url, bool? isReload)?
onUpdateVisitedHistory;
///Event fired when `window.print()` is called from JavaScript side.
@ -358,17 +394,17 @@ abstract class WebView {
///
///[hitTestResult] represents the hit result for hitting an HTML elements.
///
///**Official Android API**: https://developer.android.com/reference/android/view/View#setOnLongClickListener(android.view.View.OnLongClickListener)
///
///**Official iOS API**: https://developer.apple.com/documentation/uikit/uilongpressgesturerecognizer
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - View.setOnLongClickListener](https://developer.android.com/reference/android/view/View#setOnLongClickListener(android.view.View.OnLongClickListener)))
///- iOS ([Official API - UILongPressGestureRecognizer](https://developer.apple.com/documentation/uikit/uilongpressgesturerecognizer))
final void Function(InAppWebViewController controller,
InAppWebViewHitTestResult hitTestResult)? onLongPressHitTestResult;
///Event fired when the current page has entered full screen mode.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onShowCustomView(android.view.View,%20android.webkit.WebChromeClient.CustomViewCallback)
///
///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiwindow/1621621-didbecomevisiblenotification
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onShowCustomView](https://developer.android.com/reference/android/webkit/WebChromeClient#onShowCustomView(android.view.View,%20android.webkit.WebChromeClient.CustomViewCallback)))
///- iOS ([Official API - UIWindow.didBecomeVisibleNotification](https://developer.apple.com/documentation/uikit/uiwindow/1621621-didbecomevisiblenotification))
final void Function(InAppWebViewController controller)? onEnterFullscreen;
///Event fired when the current page has exited full screen mode.
@ -376,6 +412,10 @@ abstract class WebView {
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onHideCustomView()
///
///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiwindow/1621617-didbecomehiddennotification
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onHideCustomView](https://developer.android.com/reference/android/webkit/WebChromeClient#onHideCustomView()))
///- iOS ([Official API - UIWindow.didBecomeHiddenNotification](https://developer.apple.com/documentation/uikit/uiwindow/1621617-didbecomehiddennotification))
final void Function(InAppWebViewController controller)? onExitFullscreen;
///Called when the web view begins to receive web content.
@ -385,9 +425,9 @@ abstract class WebView {
///
///[url] represents the URL corresponding to the page navigation that triggered this callback.
///
///**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
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onPageCommitVisible](https://developer.android.com/reference/android/webkit/WebViewClient#onPageCommitVisible(android.webkit.WebView,%20java.lang.String)))
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455635-webview))
final void Function(InAppWebViewController controller, Uri? url)?
onPageCommitVisible;
@ -395,7 +435,9 @@ abstract class WebView {
///
///[title] represents the string containing the new title of the document.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedTitle(android.webkit.WebView,%20java.lang.String)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onReceivedTitle](https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedTitle(android.webkit.WebView,%20java.lang.String)))
///- iOS
final void Function(InAppWebViewController controller, String? title)?
onTitleChanged;
@ -409,7 +451,9 @@ abstract class WebView {
///
///[clampedY] is `true` if [y] was clamped to an over-scroll boundary.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebView#onOverScrolled(int,%20int,%20boolean,%20boolean)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebView.onOverScrolled](https://developer.android.com/reference/android/webkit/WebView#onOverScrolled(int,%20int,%20boolean,%20boolean)))
///- iOS
final void Function(InAppWebViewController controller, int x, int y,
bool clampedX, bool clampedY)? onOverScrolled;
@ -419,15 +463,20 @@ abstract class WebView {
///
///[newScale] The new zoom scale factor.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onScaleChanged(android.webkit.WebView,%20float,%20float)
///
///**Official iOS API**: https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619409-scrollviewdidzoom
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onScaleChanged](https://developer.android.com/reference/android/webkit/WebViewClient#onScaleChanged(android.webkit.WebView,%20float,%20float)))
///- iOS ([Official API - UIScrollViewDelegate.scrollViewDidZoom](https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619409-scrollviewdidzoom))
final void Function(
InAppWebViewController controller, double oldScale, double newScale)?
onZoomScaleChanged;
///Use [onSafeBrowsingHit] instead.
@Deprecated("Use onSafeBrowsingHit instead")
final Future<SafeBrowsingResponse?> Function(
InAppWebViewController controller,
Uri url,
SafeBrowsingThreat? threatType)? androidOnSafeBrowsingHit;
///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.
///
@ -437,11 +486,19 @@ abstract class WebView {
///
///**NOTE**: available only on Android 27+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onSafeBrowsingHit(android.webkit.WebView,%20android.webkit.WebResourceRequest,%20int,%20android.webkit.SafeBrowsingResponse)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onSafeBrowsingHit](https://developer.android.com/reference/android/webkit/WebViewClient#onSafeBrowsingHit(android.webkit.WebView,%20android.webkit.WebResourceRequest,%20int,%20android.webkit.SafeBrowsingResponse)))
final Future<SafeBrowsingResponse?> Function(
InAppWebViewController controller,
Uri url,
SafeBrowsingThreat? threatType)? androidOnSafeBrowsingHit;
SafeBrowsingThreat? threatType)? onSafeBrowsingHit;
///Use [onPermissionRequest] instead.
@Deprecated("Use onPermissionRequest instead")
final Future<PermissionRequestResponse?> Function(
InAppWebViewController controller,
String origin,
List<String> resources)? androidOnPermissionRequest;
///Event fired when the WebView is requesting permission to access the specified resources and the permission currently isn't granted or denied.
///
@ -451,11 +508,18 @@ abstract class WebView {
///
///**NOTE**: available only on Android 23+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onPermissionRequest(android.webkit.PermissionRequest)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onPermissionRequest](https://developer.android.com/reference/android/webkit/WebChromeClient#onPermissionRequest(android.webkit.PermissionRequest)))
final Future<PermissionRequestResponse?> Function(
InAppWebViewController controller,
String origin,
List<String> resources)? androidOnPermissionRequest;
List<String> resources)? onPermissionRequest;
///Use [onGeolocationPermissionsShowPrompt] instead.
@Deprecated("Use onGeolocationPermissionsShowPrompt instead")
final Future<GeolocationPermissionShowPromptResponse?> Function(
InAppWebViewController controller, String origin)?
androidOnGeolocationPermissionsShowPrompt;
///Event that notifies the host application that web content from the specified origin is attempting to use the Geolocation API, but no permission state is currently set for that origin.
///Note that for applications targeting Android N and later SDKs (API level > `Build.VERSION_CODES.M`) this method is only called for requests originating from secure origins such as https.
@ -463,22 +527,31 @@ abstract class WebView {
///
///[origin] represents the origin of the web content attempting to use the Geolocation API.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String,%20android.webkit.GeolocationPermissions.Callback)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onGeolocationPermissionsShowPrompt](https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String,%20android.webkit.GeolocationPermissions.Callback)))
final Future<GeolocationPermissionShowPromptResponse?> Function(
InAppWebViewController controller, String origin)?
androidOnGeolocationPermissionsShowPrompt;
InAppWebViewController controller, String origin)?
onGeolocationPermissionsShowPrompt;
///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.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsHidePrompt()
///Use [onGeolocationPermissionsHidePrompt] instead.
@Deprecated("Use onGeolocationPermissionsHidePrompt instead")
final void Function(InAppWebViewController controller)?
androidOnGeolocationPermissionsHidePrompt;
///Notify the host application that a request for Geolocation permissions, made with a previous call to [onGeolocationPermissionsShowPrompt] has been canceled.
///Any related UI should therefore be hidden.
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onGeolocationPermissionsHidePrompt](https://developer.android.com/reference/android/webkit/WebChromeClient#onGeolocationPermissionsHidePrompt()))
final void Function(InAppWebViewController controller)?
onGeolocationPermissionsHidePrompt;
///Use [shouldInterceptRequest] instead.
@Deprecated("Use shouldInterceptRequest instead")
final Future<WebResourceResponse?> Function(
InAppWebViewController controller, WebResourceRequest request)?
androidShouldInterceptRequest;
///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.
///Otherwise, the return response and data will be used.
@ -491,40 +564,52 @@ abstract class WebView {
///
///[request] Object containing the details of the request.
///
///**NOTE**: available only on Android. In order to be able to listen this event, you need to set [AndroidInAppWebViewOptions.useShouldInterceptRequest] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useShouldInterceptRequest] option to `true`.
///
///**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)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.shouldInterceptRequest](https://developer.android.com/reference/android/webkit/WebViewClient#shouldInterceptRequest(android.webkit.WebView,%20android.webkit.WebResourceRequest)))
final Future<WebResourceResponse?> Function(
InAppWebViewController controller, WebResourceRequest request)?
androidShouldInterceptRequest;
InAppWebViewController controller, WebResourceRequest request)?
shouldInterceptRequest;
///Use [onRenderProcessUnresponsive] instead.
@Deprecated("Use onRenderProcessUnresponsive instead")
final Future<WebViewRenderProcessAction?> Function(
InAppWebViewController controller, Uri? url)?
androidOnRenderProcessUnresponsive;
///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.
///
///If a WebView fails to process an input event, or successfully navigate to a new URL within a reasonable time frame, the renderer is considered to be unresponsive, and this callback will be called.
///
///This callback will continue to be called at regular intervals as long as the renderer remains unresponsive.
///If the renderer becomes responsive again, [androidOnRenderProcessResponsive] will be called once,
///If the renderer becomes responsive again, [onRenderProcessResponsive] will be called once,
///and this method will not subsequently be called unless another period of unresponsiveness is detected.
///
///The minimum interval between successive calls to `androidOnRenderProcessUnresponsive` is 5 seconds.
///The minimum interval between successive calls to [onRenderProcessUnresponsive] is 5 seconds.
///
///No action is taken by WebView as a result of this method call.
///Applications may choose to terminate the associated renderer via the object that is passed to this callback,
///if in multiprocess mode, however this must be accompanied by correctly handling [androidOnRenderProcessGone] for this WebView,
///if in multiprocess mode, however this must be accompanied by correctly handling [onRenderProcessGone] for this WebView,
///and all other WebViews associated with the same renderer. Failure to do so will result in application termination.
///
///**NOTE**: available only on Android 29+.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessUnresponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewRenderProcessClient.onRenderProcessUnresponsive](https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessUnresponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess)))
final Future<WebViewRenderProcessAction?> Function(
InAppWebViewController controller, Uri? url)?
onRenderProcessUnresponsive;
///Use [onRenderProcessResponsive] instead.
@Deprecated("Use onRenderProcessResponsive instead")
final Future<WebViewRenderProcessAction?> Function(
InAppWebViewController controller, Uri? url)?
androidOnRenderProcessUnresponsive;
androidOnRenderProcessResponsive;
///Event called once when an unresponsive renderer currently associated with the WebView becomes responsive.
///
///After a WebView renderer becomes unresponsive, which is notified to the application by [androidOnRenderProcessUnresponsive],
///After a WebView renderer becomes unresponsive, which is notified to the application by [onRenderProcessUnresponsive],
///it is possible for the blocking renderer task to complete, returning the renderer to a responsive state.
///In that case, this method is called once to indicate responsiveness.
///
@ -532,10 +617,17 @@ 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)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewRenderProcessClient.onRenderProcessResponsive](https://developer.android.com/reference/android/webkit/WebViewRenderProcessClient#onRenderProcessResponsive(android.webkit.WebView,%20android.webkit.WebViewRenderProcess)))
final Future<WebViewRenderProcessAction?> Function(
InAppWebViewController controller, Uri? url)?
androidOnRenderProcessResponsive;
InAppWebViewController controller, Uri? url)?
onRenderProcessResponsive;
///Use [onRenderProcessGone] instead.
@Deprecated("Use onRenderProcessGone instead")
final void Function(
InAppWebViewController controller, RenderProcessGoneDetail detail)?
androidOnRenderProcessGone;
///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.
@ -545,34 +637,49 @@ 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)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onRenderProcessGone](https://developer.android.com/reference/android/webkit/WebViewClient#onRenderProcessGone(android.webkit.WebView,%20android.webkit.RenderProcessGoneDetail)))
final void Function(
InAppWebViewController controller, RenderProcessGoneDetail detail)?
androidOnRenderProcessGone;
InAppWebViewController controller, RenderProcessGoneDetail detail)?
onRenderProcessGone;
///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)
///Use [onFormResubmission] instead.
@Deprecated('Use onFormResubmission instead')
final Future<FormResubmissionAction?> Function(
InAppWebViewController controller, Uri? url)? androidOnFormResubmission;
///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.
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onFormResubmission](https://developer.android.com/reference/android/webkit/WebViewClient#onFormResubmission(android.webkit.WebView,%20android.os.Message,%20android.os.Message)))
final Future<FormResubmissionAction?> Function(
InAppWebViewController controller, Uri? url)? onFormResubmission;
///Use [onZoomScaleChanged] instead.
@Deprecated('Use `onZoomScaleChanged` instead')
@Deprecated('Use onZoomScaleChanged instead')
final void Function(
InAppWebViewController controller, double oldScale, double newScale)?
androidOnScaleChanged;
///Use [onReceivedIcon] instead.
@Deprecated('Use onReceivedIcon instead')
final void Function(InAppWebViewController controller, Uint8List icon)?
androidOnReceivedIcon;
///Event fired when there is new favicon for the current page.
///
///[icon] represents the favicon for the current page.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedIcon(android.webkit.WebView,%20android.graphics.Bitmap)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onReceivedIcon](https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedIcon(android.webkit.WebView,%20android.graphics.Bitmap)))
final void Function(InAppWebViewController controller, Uint8List icon)?
androidOnReceivedIcon;
onReceivedIcon;
///Use [onReceivedTouchIconUrl] instead.
@Deprecated('Use onReceivedTouchIconUrl instead')
final void Function(
InAppWebViewController controller, Uri url, bool precomposed)?
androidOnReceivedTouchIconUrl;
///Event fired when there is an url for an apple-touch-icon.
///
@ -580,12 +687,17 @@ abstract class WebView {
///
///[precomposed] is `true` if the url is for a precomposed touch icon.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedTouchIconUrl(android.webkit.WebView,%20java.lang.String,%20boolean)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onReceivedTouchIconUrl](https://developer.android.com/reference/android/webkit/WebChromeClient#onReceivedTouchIconUrl(android.webkit.WebView,%20java.lang.String,%20boolean)))
final void Function(
InAppWebViewController controller, Uri url, bool precomposed)?
androidOnReceivedTouchIconUrl;
InAppWebViewController controller, Uri url, bool precomposed)?
onReceivedTouchIconUrl;
///Use [onJsBeforeUnload] instead.
@Deprecated('Use onJsBeforeUnload instead')
final Future<JsBeforeUnloadResponse?> Function(
InAppWebViewController controller,
JsBeforeUnloadRequest jsBeforeUnloadRequest)? androidOnJsBeforeUnload;
///Event fired when the client should display a dialog to confirm navigation away from the current page.
///This is the result of the `onbeforeunload` javascript event.
@ -597,51 +709,75 @@ abstract class WebView {
///
///[jsBeforeUnloadRequest] contains the message to be displayed in the alert dialog and the of the page requesting the dialog.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebChromeClient#onJsBeforeUnload(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onJsBeforeUnload](https://developer.android.com/reference/android/webkit/WebChromeClient#onJsBeforeUnload(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20android.webkit.JsResult)))
final Future<JsBeforeUnloadResponse?> Function(
InAppWebViewController controller,
JsBeforeUnloadRequest jsBeforeUnloadRequest)? androidOnJsBeforeUnload;
JsBeforeUnloadRequest jsBeforeUnloadRequest)? onJsBeforeUnload;
///Use [onReceivedLoginRequest] instead.
@Deprecated('Use onReceivedLoginRequest instead')
final void Function(
InAppWebViewController controller, LoginRequest loginRequest)?
androidOnReceivedLoginRequest;
///Event fired when a request to automatically log in the user has been processed.
///
///[loginRequest] contains the realm, account and args of the login request.
///
///**NOTE**: available only on Android.
///
///**Official Android API**: https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedLoginRequest(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20java.lang.String)
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebViewClient.onReceivedLoginRequest](https://developer.android.com/reference/android/webkit/WebViewClient#onReceivedLoginRequest(android.webkit.WebView,%20java.lang.String,%20java.lang.String,%20java.lang.String)))
final void Function(
InAppWebViewController controller, LoginRequest loginRequest)?
androidOnReceivedLoginRequest;
InAppWebViewController controller, LoginRequest loginRequest)?
onReceivedLoginRequest;
///Invoked when the web view's web content process is terminated.
///
///**NOTE**: available only on iOS.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455639-webviewwebcontentprocessdidtermi
///Use [onWebContentProcessDidTerminate] instead.
@Deprecated('Use onWebContentProcessDidTerminate instead')
final void Function(InAppWebViewController controller)?
iosOnWebContentProcessDidTerminate;
///Called when a web view receives a server redirect.
///Invoked when the web view's web content process is terminated.
///
///**NOTE**: available only on iOS.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455627-webview
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKNavigationDelegate.webViewWebContentProcessDidTerminate](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455639-webviewwebcontentprocessdidtermi))
final void Function(InAppWebViewController controller)?
onWebContentProcessDidTerminate;
///Use [onDidReceiveServerRedirectForProvisionalNavigation] instead.
@Deprecated('Use onDidReceiveServerRedirectForProvisionalNavigation instead')
final void Function(InAppWebViewController controller)?
iosOnDidReceiveServerRedirectForProvisionalNavigation;
///Called when a web view receives a server redirect.
///
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455627-webview))
final void Function(InAppWebViewController controller)?
onDidReceiveServerRedirectForProvisionalNavigation;
///Use [onNavigationResponse] instead.
@Deprecated('Use onNavigationResponse instead')
final Future<IOSNavigationResponseAction?> Function(
InAppWebViewController controller,
IOSWKNavigationResponse navigationResponse)? iosOnNavigationResponse;
///Called when a web view asks for permission to navigate to new content after the response to the navigation request is known.
///
///[navigationResponse] represents the navigation response.
///
///**NOTE**: available only on iOS. In order to be able to listen this event, you need to set [IOSInAppWebViewOptions.useOnNavigationResponse] option to `true`.
///**NOTE**: In order to be able to listen this event, you need to set [InAppWebViewSettings.useOnNavigationResponse] option to `true`.
///
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview
final Future<IOSNavigationResponseAction?> Function(
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview))
final Future<NavigationResponseAction?> Function(
InAppWebViewController controller,
IOSWKNavigationResponse navigationResponse)? iosOnNavigationResponse;
NavigationResponse navigationResponse)? onNavigationResponse;
///Use [shouldAllowDeprecatedTLS] instead.
@Deprecated('Use shouldAllowDeprecatedTLS instead')
final Future<IOSShouldAllowDeprecatedTLSAction?> Function(
InAppWebViewController controller,
URLAuthenticationChallenge challenge)? iosShouldAllowDeprecatedTLS;
///Called when a web view asks whether to continue with a connection that uses a deprecated version of TLS (v1.0 and v1.1).
///
@ -649,10 +785,11 @@ abstract class WebView {
///
///**NOTE**: available only on iOS 14.0+.
///
///**Official iOS API**: https://developer.apple.com/documentation/webkit/wknavigationdelegate/3601237-webview
final Future<IOSShouldAllowDeprecatedTLSAction?> Function(
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKNavigationDelegate.webView](https://developer.apple.com/documentation/webkit/wknavigationdelegate/3601237-webview))
final Future<ShouldAllowDeprecatedTLSAction?> Function(
InAppWebViewController controller,
URLAuthenticationChallenge challenge)? iosShouldAllowDeprecatedTLS;
URLAuthenticationChallenge challenge)? shouldAllowDeprecatedTLS;
///Initial url request that will be loaded.
///
@ -665,9 +802,13 @@ abstract class WebView {
///Initial [InAppWebViewInitialData] that will be loaded.
final InAppWebViewInitialData? initialData;
///Initial options that will be used.
///Use [initialSettings] instead.
@Deprecated('Use initialSettings instead')
final InAppWebViewGroupOptions? initialOptions;
///Initial settings that will be used.
final InAppWebViewSettings? initialSettings;
///Context menu which contains custom menu items to be shown when [ContextMenu] is presented.
final ContextMenu? contextMenu;
@ -682,7 +823,7 @@ abstract class WebView {
///Represents the pull-to-refresh feature controller.
///
///**NOTE for Android**: to be able to use the "pull-to-refresh" feature, [AndroidInAppWebViewOptions.useHybridComposition] must be `true`.
///**NOTE for Android**: to be able to use the "pull-to-refresh" feature, [InAppWebViewSettings.useHybridComposition] must be `true`.
final PullToRefreshController? pullToRefreshController;
///Represents the WebView native implementation to be used.
@ -701,7 +842,7 @@ abstract class WebView {
this.shouldOverrideUrlLoading,
this.onLoadResource,
this.onScrollChanged,
@Deprecated('Use `onDownloadStartRequest` instead')
@Deprecated('Use onDownloadStartRequest instead')
this.onDownloadStart,
this.onDownloadStartRequest,
this.onLoadResourceCustomScheme,
@ -729,29 +870,46 @@ abstract class WebView {
this.onWindowBlur,
this.onOverScrolled,
this.onZoomScaleChanged,
this.androidOnSafeBrowsingHit,
this.androidOnPermissionRequest,
this.androidOnGeolocationPermissionsShowPrompt,
this.androidOnGeolocationPermissionsHidePrompt,
this.androidShouldInterceptRequest,
this.androidOnRenderProcessGone,
this.androidOnRenderProcessResponsive,
this.androidOnRenderProcessUnresponsive,
this.androidOnFormResubmission,
@Deprecated('Use `onZoomScaleChanged` instead')
this.androidOnScaleChanged,
this.androidOnReceivedIcon,
this.androidOnReceivedTouchIconUrl,
this.androidOnJsBeforeUnload,
this.androidOnReceivedLoginRequest,
this.iosOnWebContentProcessDidTerminate,
this.iosOnDidReceiveServerRedirectForProvisionalNavigation,
this.iosOnNavigationResponse,
this.iosShouldAllowDeprecatedTLS,
@Deprecated('Use onSafeBrowsingHit instead') this.androidOnSafeBrowsingHit,
this.onSafeBrowsingHit,
@Deprecated('Use onPermissionRequest instead') this.androidOnPermissionRequest,
this.onPermissionRequest,
@Deprecated('Use onGeolocationPermissionsShowPrompt instead') this.androidOnGeolocationPermissionsShowPrompt,
this.onGeolocationPermissionsShowPrompt,
@Deprecated('Use onGeolocationPermissionsHidePrompt instead') this.androidOnGeolocationPermissionsHidePrompt,
this.onGeolocationPermissionsHidePrompt,
@Deprecated('Use shouldInterceptRequest instead') this.androidShouldInterceptRequest,
this.shouldInterceptRequest,
@Deprecated('Use onRenderProcessGone instead') this.androidOnRenderProcessGone,
this.onRenderProcessGone,
@Deprecated('Use onRenderProcessResponsive instead') this.androidOnRenderProcessResponsive,
this.onRenderProcessResponsive,
@Deprecated('Use onRenderProcessUnresponsive instead') this.androidOnRenderProcessUnresponsive,
this.onRenderProcessUnresponsive,
@Deprecated('Use onFormResubmission instead') this.androidOnFormResubmission,
this.onFormResubmission,
@Deprecated('Use onZoomScaleChanged instead') this.androidOnScaleChanged,
@Deprecated('Use onReceivedIcon instead') this.androidOnReceivedIcon,
this.onReceivedIcon,
@Deprecated('Use onReceivedTouchIconUrl instead') this.androidOnReceivedTouchIconUrl,
this.onReceivedTouchIconUrl,
@Deprecated('Use onJsBeforeUnload instead') this.androidOnJsBeforeUnload,
this.onJsBeforeUnload,
@Deprecated('Use onReceivedLoginRequest instead') this.androidOnReceivedLoginRequest,
this.onReceivedLoginRequest,
@Deprecated('Use onWebContentProcessDidTerminate instead') this.iosOnWebContentProcessDidTerminate,
this.onWebContentProcessDidTerminate,
@Deprecated('Use onDidReceiveServerRedirectForProvisionalNavigation instead') this.iosOnDidReceiveServerRedirectForProvisionalNavigation,
this.onDidReceiveServerRedirectForProvisionalNavigation,
@Deprecated('Use onNavigationResponse instead') this.iosOnNavigationResponse,
this.onNavigationResponse,
@Deprecated('Use shouldAllowDeprecatedTLS instead') this.iosShouldAllowDeprecatedTLS,
this.shouldAllowDeprecatedTLS,
this.initialUrlRequest,
this.initialFile,
this.initialData,
this.initialOptions,
@Deprecated('Use initialSettings instead') this.initialOptions,
this.initialSettings,
this.contextMenu,
this.initialUserScripts,
this.pullToRefreshController,

View File

@ -5,7 +5,7 @@ import '../in_app_webview/webview.dart';
import '../in_app_browser/in_app_browser.dart';
import '../util.dart';
import '../types.dart';
import '../in_app_webview/android/in_app_webview_options.dart';
import '../in_app_webview/in_app_webview_settings.dart';
import 'pull_to_refresh_options.dart';
///A standard controller that can initiate the refreshing of a scroll views contents.
@ -14,7 +14,7 @@ import 'pull_to_refresh_options.dart';
///All the methods should be called only when the WebView has been created or is already running
///(for example [WebView.onWebViewCreated] or [InAppBrowser.onBrowserCreated]).
///
///**NOTE for Android**: to be able to use the "pull-to-refresh" feature, [AndroidInAppWebViewOptions.useHybridComposition] must be `true`.
///**NOTE for Android**: to be able to use the "pull-to-refresh" feature, [InAppWebViewSettings.useHybridComposition] must be `true`.
class PullToRefreshController {
late PullToRefreshOptions options;
MethodChannel? _channel;
@ -115,10 +115,18 @@ class PullToRefreshController {
return await _channel?.invokeMethod('getDefaultSlingshotDistance', args);
}
///Sets the size of the refresh indicator. One of [AndroidPullToRefreshSize.DEFAULT], or [AndroidPullToRefreshSize.LARGE].
///Use [setIndicatorSize] instead.
@Deprecated("Use setIndicatorSize instead")
Future<void> setSize(AndroidPullToRefreshSize size) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('size', () => size.toValue());
await _channel?.invokeMethod('setSize', args);
}
///Sets the size of the refresh indicator. One of [PullToRefreshSize.DEFAULT], or [PullToRefreshSize.LARGE].
///
///**NOTE**: Available only on Android.
Future<void> setSize(AndroidPullToRefreshSize size) async {
Future<void> setIndicatorSize(PullToRefreshSize size) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('size', () => size.toValue());
await _channel?.invokeMethod('setSize', args);

File diff suppressed because it is too large Load Diff

View File

@ -7,6 +7,9 @@ import '../_static_channel.dart';
///Class that is used to manage the JavaScript storage APIs provided by the WebView.
///It manages the Application Cache API, the Web SQL Database API and the HTML5 Web Storage API.
///
///Use [WebStorageManager] instead.
@Deprecated("Use WebStorageManager instead")
class AndroidWebStorageManager {
static MethodChannel _staticChannel = WEB_STORAGE_STATIC_CHANNEL;

View File

@ -9,6 +9,9 @@ import '../_static_channel.dart';
///This includes cookies, disk and memory caches, and persistent data such as WebSQL, IndexedDB databases, and local storage.
///
///**NOTE**: available on iOS 9.0+.
///
///Use [WebStorageManager] instead.
@Deprecated("Use WebStorageManager instead")
class IOSWebStorageManager {
static MethodChannel _staticChannel = WEB_STORAGE_STATIC_CHANNEL;

View File

@ -6,6 +6,9 @@ import '_static_channel.dart';
import 'android/web_storage_manager.dart';
import 'ios/web_storage_manager.dart';
import '../types.dart';
///Class that implements a singleton object (shared instance) which manages the web storage used by WebView instances.
///On Android, it is implemented using [WebStorage](https://developer.android.com/reference/android/webkit/WebStorage.html).
///On iOS, it is implemented using [WKWebsiteDataStore.default()](https://developer.apple.com/documentation/webkit/wkwebsitedatastore).
@ -15,7 +18,12 @@ class WebStorageManager {
static WebStorageManager? _instance;
static const MethodChannel _staticChannel = WEB_STORAGE_STATIC_CHANNEL;
///Use [WebStorageManager] instead.
@Deprecated("Use WebStorageManager instead")
AndroidWebStorageManager android = AndroidWebStorageManager();
///Use [WebStorageManager] instead.
@Deprecated("Use WebStorageManager instead")
IOSWebStorageManager ios = IOSWebStorageManager();
///Gets the WebStorage manager shared instance.
@ -30,4 +38,154 @@ class WebStorageManager {
}
static Future<dynamic> _handleMethod(MethodCall call) async {}
///Gets the origins currently using either the Application Cache or Web SQL Database APIs.
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebStorage.getOrigins](https://developer.android.com/reference/android/webkit/WebStorage#getOrigins(android.webkit.ValueCallback%3Cjava.util.Map%3E)))
Future<List<WebStorageOrigin>> getOrigins() async {
List<WebStorageOrigin> originsList = [];
Map<String, dynamic> args = <String, dynamic>{};
List<Map<dynamic, dynamic>> origins =
(await _staticChannel.invokeMethod('getOrigins', args))
.cast<Map<dynamic, dynamic>>();
for (var origin in origins) {
originsList.add(WebStorageOrigin(
origin: origin["origin"],
quota: origin["quota"],
usage: origin["usage"]));
}
return originsList;
}
///Clears all storage currently being used by the JavaScript storage APIs.
///This includes the Application Cache, Web SQL Database and the HTML5 Web Storage APIs.
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebStorage.deleteAllData](https://developer.android.com/reference/android/webkit/WebStorage#deleteAllData()))
Future<void> deleteAllData() async {
Map<String, dynamic> args = <String, dynamic>{};
await _staticChannel.invokeMethod('deleteAllData', args);
}
///Clears the storage currently being used by both the Application Cache and Web SQL Database APIs by the given [origin].
///The origin is specified using its string representation.
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebStorage.deleteOrigin](https://developer.android.com/reference/android/webkit/WebStorage#deleteOrigin(java.lang.String)))
Future<void> deleteOrigin({required String origin}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("origin", () => origin);
await _staticChannel.invokeMethod('deleteOrigin', args);
}
///Gets the storage quota for the Web SQL Database API for the given [origin].
///The quota is given in bytes and the origin is specified using its string representation.
///Note that a quota is not enforced on a per-origin basis for the Application Cache API.
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebStorage.getQuotaForOrigin](https://developer.android.com/reference/android/webkit/WebStorage#getQuotaForOrigin(java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.Long%3E)))
Future<int> getQuotaForOrigin({required String origin}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("origin", () => origin);
return await _staticChannel.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].
///The amount is given in bytes and the origin is specified using its string representation.
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebStorage.getUsageForOrigin](https://developer.android.com/reference/android/webkit/WebStorage#getUsageForOrigin(java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.Long%3E)))
Future<int> getUsageForOrigin({required String origin}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("origin", () => origin);
return await _staticChannel.invokeMethod('getUsageForOrigin', args);
}
///Fetches data records containing the given website data types.
///
///[dataTypes] represents the website data types to fetch records for.
///
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKWebsiteDataStore.fetchDataRecords](https://developer.apple.com/documentation/webkit/wkwebsitedatastore/1532932-fetchdatarecords))
Future<List<WebsiteDataRecord>> fetchDataRecords(
{required Set<WebsiteDataType> dataTypes}) async {
List<WebsiteDataRecord> recordList = [];
List<String> dataTypesList = [];
for (var dataType in dataTypes) {
dataTypesList.add(dataType.toValue());
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("dataTypes", () => dataTypesList);
List<Map<dynamic, dynamic>> records =
(await _staticChannel.invokeMethod('fetchDataRecords', args))
.cast<Map<dynamic, dynamic>>();
for (var record in records) {
List<String> dataTypesString = record["dataTypes"].cast<String>();
Set<WebsiteDataType> dataTypes = Set();
for (var dataTypeValue in dataTypesString) {
var dataType = WebsiteDataType.fromValue(dataTypeValue);
if (dataType != null) {
dataTypes.add(dataType);
}
}
recordList.add(WebsiteDataRecord(
displayName: record["displayName"], dataTypes: dataTypes));
}
return recordList;
}
///Removes website data of the given types for the given data records.
///
///[dataTypes] represents the website data types that should be removed.
///
///[dataRecords] represents the website data records to delete website data for.
///
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKWebsiteDataStore.removeData](https://developer.apple.com/documentation/webkit/wkwebsitedatastore/1532936-removedata))
Future<void> removeDataFor(
{required Set<WebsiteDataType> dataTypes,
required List<WebsiteDataRecord> dataRecords}) async {
List<String> dataTypesList = [];
for (var dataType in dataTypes) {
dataTypesList.add(dataType.toValue());
}
List<Map<String, dynamic>> recordList = [];
for (var record in dataRecords) {
recordList.add(record.toMap());
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("dataTypes", () => dataTypesList);
args.putIfAbsent("recordList", () => recordList);
await _staticChannel.invokeMethod('removeDataFor', args);
}
///Removes all website data of the given types that has been modified since the given date.
///
///[dataTypes] represents the website data types that should be removed.
///
///[date] represents a date. All website data modified after this date will be removed.
///
///**Supported Platforms/Implementations**:
///- iOS ([Official API - WKWebsiteDataStore.removeData](https://developer.apple.com/documentation/webkit/wkwebsitedatastore/1532938-removedata))
Future<void> removeDataModifiedSince(
{required Set<WebsiteDataType> dataTypes,
required DateTime date}) async {
List<String> dataTypesList = [];
for (var dataType in dataTypes) {
dataTypesList.add(dataType.toValue());
}
var timestamp = date.millisecondsSinceEpoch;
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("dataTypes", () => dataTypesList);
args.putIfAbsent("timestamp", () => timestamp);
await _staticChannel.invokeMethod('removeDataModifiedSince', args);
}
}