This commit is contained in:
Lorenzo Pichilli 2022-04-23 17:49:29 +02:00
commit dd9043ccf5
56 changed files with 900 additions and 463 deletions

View File

@ -7,6 +7,19 @@
- Added support for `onPermissionRequest` event on iOS 15.0+
- Updated `getMetaThemeColor` on iOS 15.0+
## 5.4.1+1
- Fixed Android default context menu over custom context menu on API Level 31+
## 5.4.1
- Managed iOS native `detachFromEngine` flutter plugin event and updated `dispose` methods
- Updated Android native `HeadlessInAppWebViewManager.dispose` and `HeadlessInAppWebView.dispose` methods
## 5.4.0+3
- Fixed Android error in some cases when calling `setServiceWorkerClient` java method on `ServiceWorkerManager` initialization
## 5.4.0+2
- Fixed Android `ChromeCustomTabsActivity` not responding to the `ActionBroadcastReceiver`

View File

@ -59,6 +59,4 @@ Add `flutter_inappwebview` as a [dependency in your pubspec.yaml file](https://f
## Support
Use the [develop branch](https://github.com/pichillilorenzo/flutter_inappwebview/tree/develop) when making a pull request.
Did you find this plugin useful? Please consider to [make a donation](https://inappwebview.dev/donate/) to help improve it!

View File

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

View File

@ -38,50 +38,6 @@ public class ServiceWorkerManager implements MethodChannel.MethodCallHandler {
channel.setMethodCallHandler(this);
if (WebViewFeature.isFeatureSupported(WebViewFeature.SERVICE_WORKER_BASIC_USAGE)) {
serviceWorkerController = ServiceWorkerControllerCompat.getInstance();
serviceWorkerController.setServiceWorkerClient(new ServiceWorkerClientCompat() {
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(@NonNull WebResourceRequest request) {
final Map<String, Object> obj = new HashMap<>();
obj.put("url", request.getUrl().toString());
obj.put("method", request.getMethod());
obj.put("headers", request.getRequestHeaders());
obj.put("isForMainFrame", request.isForMainFrame());
obj.put("hasGesture", request.hasGesture());
obj.put("isRedirect", request.isRedirect());
Util.WaitFlutterResult flutterResult;
try {
flutterResult = Util.invokeMethodAndWait(channel, "shouldInterceptRequest", obj);
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
if (flutterResult.error != null) {
Log.e(LOG_TAG, flutterResult.error);
}
else if (flutterResult.result != null) {
Map<String, Object> res = (Map<String, Object>) flutterResult.result;
String contentType = (String) res.get("contentType");
String contentEncoding = (String) res.get("contentEncoding");
byte[] data = (byte[]) res.get("data");
Map<String, String> responseHeaders = (Map<String, String>) res.get("headers");
Integer statusCode = (Integer) res.get("statusCode");
String reasonPhrase = (String) res.get("reasonPhrase");
ByteArrayInputStream inputStream = (data != null) ? new ByteArrayInputStream(data) : null;
if ((responseHeaders == null && statusCode == null && reasonPhrase == null) || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return new WebResourceResponse(contentType, contentEncoding, inputStream);
} else {
return new WebResourceResponse(contentType, contentEncoding, statusCode, reasonPhrase, responseHeaders, inputStream);
}
}
return null;
}
});
} else {
serviceWorkerController = null;
}
@ -92,6 +48,13 @@ public class ServiceWorkerManager implements MethodChannel.MethodCallHandler {
ServiceWorkerWebSettingsCompat serviceWorkerWebSettings = (serviceWorkerController != null) ? serviceWorkerController.getServiceWorkerWebSettings() : null;
switch (call.method) {
case "setServiceWorkerClient":
{
Boolean isNull = (Boolean) call.argument("isNull");
setServiceWorkerClient(isNull);
}
result.success(true);
break;
case "getAllowContentAccess":
if (serviceWorkerWebSettings != null && WebViewFeature.isFeatureSupported(WebViewFeature.SERVICE_WORKER_CONTENT_ACCESS)) {
result.success(serviceWorkerWebSettings.getAllowContentAccess());
@ -152,9 +115,62 @@ public class ServiceWorkerManager implements MethodChannel.MethodCallHandler {
result.notImplemented();
}
}
private void setServiceWorkerClient(Boolean isNull) {
if (serviceWorkerController != null) {
serviceWorkerController.setServiceWorkerClient(isNull ? null : new ServiceWorkerClientCompat() {
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(@NonNull WebResourceRequest request) {
final Map<String, Object> obj = new HashMap<>();
obj.put("url", request.getUrl().toString());
obj.put("method", request.getMethod());
obj.put("headers", request.getRequestHeaders());
obj.put("isForMainFrame", request.isForMainFrame());
obj.put("hasGesture", request.hasGesture());
obj.put("isRedirect", request.isRedirect());
Util.WaitFlutterResult flutterResult;
try {
flutterResult = Util.invokeMethodAndWait(channel, "shouldInterceptRequest", obj);
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
if (flutterResult.error != null) {
Log.e(LOG_TAG, flutterResult.error);
}
else if (flutterResult.result != null) {
Map<String, Object> res = (Map<String, Object>) flutterResult.result;
String contentType = (String) res.get("contentType");
String contentEncoding = (String) res.get("contentEncoding");
byte[] data = (byte[]) res.get("data");
Map<String, String> responseHeaders = (Map<String, String>) res.get("headers");
Integer statusCode = (Integer) res.get("statusCode");
String reasonPhrase = (String) res.get("reasonPhrase");
ByteArrayInputStream inputStream = (data != null) ? new ByteArrayInputStream(data) : null;
if ((responseHeaders == null && statusCode == null && reasonPhrase == null) || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return new WebResourceResponse(contentType, contentEncoding, inputStream);
} else {
return new WebResourceResponse(contentType, contentEncoding, statusCode, reasonPhrase, responseHeaders, inputStream);
}
}
return null;
}
});
}
}
public void dispose() {
channel.setMethodCallHandler(null);
if (serviceWorkerController != null) {
serviceWorkerController.setServiceWorkerClient(null);
serviceWorkerController = null;
}
plugin = null;
}
}

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.IWebViewSettings;
import com.pichillilorenzo.flutter_inappwebview.ISettings;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ChromeCustomTabsSettings implements IWebViewSettings<ChromeCustomTabsActivity> {
public class ChromeCustomTabsSettings implements ISettings<ChromeCustomTabsActivity> {
final static String LOG_TAG = "ChromeCustomTabsSettings";

View File

@ -110,12 +110,16 @@ public class HeadlessInAppWebView implements MethodChannel.MethodCallHandler {
public void dispose() {
channel.setMethodCallHandler(null);
HeadlessInAppWebViewManager.webViews.remove(id);
ViewGroup contentView = (ViewGroup) plugin.activity.findViewById(android.R.id.content);
ViewGroup mainView = (ViewGroup) (contentView).getChildAt(0);
if (mainView != null) {
mainView.removeView(flutterWebView.getView());
if (plugin != null) {
ViewGroup contentView = (ViewGroup) plugin.activity.findViewById(android.R.id.content);
ViewGroup mainView = (ViewGroup) (contentView).getChildAt(0);
if (mainView != null && flutterWebView != null) {
mainView.removeView(flutterWebView.getView());
}
}
if (flutterWebView != null) {
flutterWebView.dispose();
}
flutterWebView.dispose();
flutterWebView = null;
plugin = null;
}

View File

@ -26,7 +26,9 @@ import androidx.annotation.Nullable;
import com.pichillilorenzo.flutter_inappwebview.InAppWebViewFlutterPlugin;
import com.pichillilorenzo.flutter_inappwebview.in_app_webview.FlutterWebView;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.flutter.plugin.common.MethodCall;
@ -77,6 +79,10 @@ public class HeadlessInAppWebViewManager implements MethodChannel.MethodCallHand
public void dispose() {
channel.setMethodCallHandler(null);
Collection<HeadlessInAppWebView> headlessInAppWebViews = webViews.values();
for (HeadlessInAppWebView headlessInAppWebView : headlessInAppWebViews) {
headlessInAppWebView.dispose();
}
webViews.clear();
}
}

View File

@ -2,13 +2,13 @@ package com.pichillilorenzo.flutter_inappwebview.in_app_browser;
import androidx.annotation.Nullable;
import com.pichillilorenzo.flutter_inappwebview.IWebViewSettings;
import com.pichillilorenzo.flutter_inappwebview.ISettings;
import com.pichillilorenzo.flutter_inappwebview.R;
import java.util.HashMap;
import java.util.Map;
public class InAppBrowserSettings implements IWebViewSettings<InAppBrowserActivity> {
public class InAppBrowserSettings implements ISettings<InAppBrowserActivity> {
public static final String LOG_TAG = "InAppBrowserSettings";

View File

@ -1,16 +1,16 @@
package com.pichillilorenzo.flutter_inappwebview.in_app_webview;
import com.pichillilorenzo.flutter_inappwebview.IWebViewSettings;
import com.pichillilorenzo.flutter_inappwebview.ISettings;
import java.util.HashMap;
import java.util.Map;
public class ContextMenuOptions implements IWebViewSettings<Object> {
public class ContextMenuSettings implements ISettings<Object> {
public static final String LOG_TAG = "ContextMenuOptions";
public Boolean hideDefaultSystemContextMenuItems = false;
public ContextMenuOptions parse(Map<String, Object> options) {
public ContextMenuSettings parse(Map<String, Object> options) {
for (Map.Entry<String, Object> pair : options.entrySet()) {
String key = pair.getKey();
Object value = pair.getValue();

View File

@ -54,8 +54,6 @@ import androidx.webkit.WebViewCompat;
import androidx.webkit.WebViewFeature;
import com.pichillilorenzo.flutter_inappwebview.InAppWebViewFlutterPlugin;
import com.pichillilorenzo.flutter_inappwebview.types.DownloadStartRequest;
import com.pichillilorenzo.flutter_inappwebview.types.InAppWebViewInterface;
import com.pichillilorenzo.flutter_inappwebview.JavaScriptBridgeInterface;
import com.pichillilorenzo.flutter_inappwebview.R;
import com.pichillilorenzo.flutter_inappwebview.Util;
@ -76,6 +74,8 @@ import com.pichillilorenzo.flutter_inappwebview.plugin_scripts_js.PrintJS;
import com.pichillilorenzo.flutter_inappwebview.plugin_scripts_js.PromisePolyfillJS;
import com.pichillilorenzo.flutter_inappwebview.pull_to_refresh.PullToRefreshLayout;
import com.pichillilorenzo.flutter_inappwebview.types.ContentWorld;
import com.pichillilorenzo.flutter_inappwebview.types.DownloadStartRequest;
import com.pichillilorenzo.flutter_inappwebview.types.InAppWebViewInterface;
import com.pichillilorenzo.flutter_inappwebview.types.PluginScript;
import com.pichillilorenzo.flutter_inappwebview.types.PreferredContentModeOptionType;
import com.pichillilorenzo.flutter_inappwebview.types.URLRequest;
@ -1356,8 +1356,16 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
}
Menu actionMenu = actionMode.getMenu();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
actionMode.hide(3000);
}
List<MenuItem> defaultMenuItems = new ArrayList<>();
for (int i = 0; i < actionMenu.size(); i++) {
defaultMenuItems.add(actionMenu.getItem(i));
}
actionMenu.clear();
actionMode.finish();
if (customSettings.disableContextMenu) {
actionMenu.clear();
return actionMode;
}
@ -1367,19 +1375,18 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
LinearLayout menuItemListLayout = (LinearLayout) horizontalScrollView.getChildAt(0);
List<Map<String, Object>> customMenuItems = new ArrayList<>();
ContextMenuOptions contextMenuOptions = new ContextMenuOptions();
ContextMenuSettings contextMenuSettings = new ContextMenuSettings();
if (contextMenu != null) {
customMenuItems = (List<Map<String, Object>>) contextMenu.get("menuItems");
Map<String, Object> contextMenuOptionsMap = (Map<String, Object>) contextMenu.get("options");
if (contextMenuOptionsMap != null) {
contextMenuOptions.parse(contextMenuOptionsMap);
Map<String, Object> contextMenuSettingsMap = (Map<String, Object>) contextMenu.get("settings");
if (contextMenuSettingsMap != null) {
contextMenuSettings.parse(contextMenuSettingsMap);
}
}
customMenuItems = customMenuItems == null ? new ArrayList<Map<String, Object>>() : customMenuItems;
if (contextMenuOptions.hideDefaultSystemContextMenuItems == null || !contextMenuOptions.hideDefaultSystemContextMenuItems) {
for (int i = 0; i < actionMenu.size(); i++) {
final MenuItem menuItem = actionMenu.getItem(i);
if (contextMenuSettings.hideDefaultSystemContextMenuItems == null || !contextMenuSettings.hideDefaultSystemContextMenuItems) {
for (final MenuItem menuItem : defaultMenuItems) {
final int itemId = menuItem.getItemId();
final String itemTitle = menuItem.getTitle().toString();
@ -1393,6 +1400,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
callback.onActionItemClicked(actionMode, menuItem);
Map<String, Object> obj = new HashMap<>();
obj.put("id", itemId);
obj.put("androidId", itemId);
obj.put("iosId", null);
obj.put("title", itemTitle);
@ -1406,7 +1414,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
}
for (final Map<String, Object> menuItem : customMenuItems) {
final int itemId = (int) menuItem.get("androidId");
final int itemId = (int) menuItem.get("id");
final String itemTitle = (String) menuItem.get("title");
TextView text = (TextView) LayoutInflater.from(this.getContext())
.inflate(R.layout.floating_action_mode_item, this, false);
@ -1417,6 +1425,7 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
hideContextMenu();
Map<String, Object> obj = new HashMap<>();
obj.put("id", itemId);
obj.put("androidId", itemId);
obj.put("iosId", null);
obj.put("title", itemTitle);
@ -1456,7 +1465,6 @@ final public class InAppWebView extends InputAwareWebView implements InAppWebVie
checkContextMenuShouldBeClosedTask.run();
}
}
actionMenu.clear();
return actionMode;
}

View File

@ -6,7 +6,7 @@ import android.webkit.WebSettings;
import androidx.annotation.Nullable;
import com.pichillilorenzo.flutter_inappwebview.IWebViewSettings;
import com.pichillilorenzo.flutter_inappwebview.ISettings;
import com.pichillilorenzo.flutter_inappwebview.types.InAppWebViewInterface;
import com.pichillilorenzo.flutter_inappwebview.types.PreferredContentModeOptionType;
@ -18,7 +18,7 @@ import java.util.Map;
import static android.webkit.WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
import static android.webkit.WebSettings.LayoutAlgorithm.NORMAL;
public class InAppWebViewSettings implements IWebViewSettings<InAppWebViewInterface> {
public class InAppWebViewSettings implements ISettings<InAppWebViewInterface> {
public static final String LOG_TAG = "InAppWebViewSettings";

View File

@ -2,12 +2,12 @@ package com.pichillilorenzo.flutter_inappwebview.pull_to_refresh;
import androidx.annotation.Nullable;
import com.pichillilorenzo.flutter_inappwebview.IWebViewSettings;
import com.pichillilorenzo.flutter_inappwebview.ISettings;
import java.util.HashMap;
import java.util.Map;
public class PullToRefreshSettings implements IWebViewSettings<PullToRefreshLayout> {
public class PullToRefreshSettings implements ISettings<PullToRefreshLayout> {
public static final String LOG_TAG = "PullToRefreshSettings";
public Boolean enabled = true;

View File

@ -25,6 +25,7 @@ public class NavigationAction {
navigationActionMap.put("navigationType", null);
navigationActionMap.put("sourceFrame", null);
navigationActionMap.put("targetFrame", null);
navigationActionMap.put("shouldPerformDownload", null);
return navigationActionMap;
}

View File

@ -77,7 +77,7 @@ void main() {
AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
}
group('InAppWebView', () {
group('InAppWebView', () {
testWidgets('initialUrlRequest', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
await tester.pumpWidget(
@ -1709,13 +1709,14 @@ void main() {
group('intercept ajax request', () {
testWidgets('send string data', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer shouldInterceptAjaxPostRequestCompleter =
Completer<void>();
Completer<void>();
final Completer<Map<String, dynamic>> onAjaxReadyStateChangeCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
final Completer<Map<String, dynamic>> onAjaxProgressCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
@ -1745,9 +1746,9 @@ void main() {
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
clearCache: true,
useShouldInterceptAjaxRequest: true,
)),
clearCache: true,
useShouldInterceptAjaxRequest: true,
)),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
@ -1780,9 +1781,9 @@ void main() {
await shouldInterceptAjaxPostRequestCompleter.future;
final Map<String, dynamic> onAjaxReadyStateChangeValue =
await onAjaxReadyStateChangeCompleter.future;
await onAjaxReadyStateChangeCompleter.future;
final Map<String, dynamic> onAjaxProgressValue =
await onAjaxProgressCompleter.future;
await onAjaxProgressCompleter.future;
expect(
mapEquals(onAjaxReadyStateChangeValue,
@ -1795,13 +1796,14 @@ void main() {
});
testWidgets('send json data', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer shouldInterceptAjaxPostRequestCompleter =
Completer<void>();
Completer<void>();
final Completer<Map<String, dynamic>> onAjaxReadyStateChangeCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
final Completer<Map<String, dynamic>> onAjaxProgressCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
@ -1835,15 +1837,16 @@ void main() {
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
clearCache: true,
useShouldInterceptAjaxRequest: true,
)),
clearCache: true,
useShouldInterceptAjaxRequest: true,
)),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
shouldInterceptAjaxRequest: (controller, ajaxRequest) async {
String data = ajaxRequest.data;
assert(data.contains('"firstname":"Foo"') && data.contains('"lastname":"Bar"'));
assert(data.contains('"firstname":"Foo"') &&
data.contains('"lastname":"Bar"'));
ajaxRequest.responseType = 'json';
ajaxRequest.data = '{"firstname": "Foo2", "lastname": "Bar2"}';
@ -1871,9 +1874,9 @@ void main() {
await shouldInterceptAjaxPostRequestCompleter.future;
final Map<String, dynamic> onAjaxReadyStateChangeValue =
await onAjaxReadyStateChangeCompleter.future;
await onAjaxReadyStateChangeCompleter.future;
final Map<String, dynamic> onAjaxProgressValue =
await onAjaxProgressCompleter.future;
await onAjaxProgressCompleter.future;
expect(
mapEquals(onAjaxReadyStateChangeValue,
@ -1886,13 +1889,14 @@ void main() {
});
testWidgets('send URLSearchParams data', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer shouldInterceptAjaxPostRequestCompleter =
Completer<void>();
Completer<void>();
final Completer<Map<String, dynamic>> onAjaxReadyStateChangeCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
final Completer<Map<String, dynamic>> onAjaxProgressCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
@ -1924,9 +1928,9 @@ void main() {
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
clearCache: true,
useShouldInterceptAjaxRequest: true,
)),
clearCache: true,
useShouldInterceptAjaxRequest: true,
)),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
@ -1959,9 +1963,9 @@ void main() {
await shouldInterceptAjaxPostRequestCompleter.future;
final Map<String, dynamic> onAjaxReadyStateChangeValue =
await onAjaxReadyStateChangeCompleter.future;
await onAjaxReadyStateChangeCompleter.future;
final Map<String, dynamic> onAjaxProgressValue =
await onAjaxProgressCompleter.future;
await onAjaxProgressCompleter.future;
expect(
mapEquals(onAjaxReadyStateChangeValue,
@ -1974,13 +1978,14 @@ void main() {
});
testWidgets('send FormData', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer shouldInterceptAjaxPostRequestCompleter =
Completer<void>();
Completer<void>();
final Completer<Map<String, dynamic>> onAjaxReadyStateChangeCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
final Completer<Map<String, dynamic>> onAjaxProgressCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
@ -2012,9 +2017,9 @@ void main() {
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
clearCache: true,
useShouldInterceptAjaxRequest: true,
)),
clearCache: true,
useShouldInterceptAjaxRequest: true,
)),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
@ -2025,7 +2030,9 @@ void main() {
var bodyString = String.fromCharCodes(body);
assert(bodyString.indexOf("WebKitFormBoundary") >= 0);
ajaxRequest.data = utf8.encode(bodyString.replaceFirst("Foo", "Foo2").replaceFirst("Bar", "Bar2"));
ajaxRequest.data = utf8.encode(bodyString
.replaceFirst("Foo", "Foo2")
.replaceFirst("Bar", "Bar2"));
ajaxRequest.responseType = 'json';
shouldInterceptAjaxPostRequestCompleter.complete(controller);
return ajaxRequest;
@ -2051,9 +2058,9 @@ void main() {
await shouldInterceptAjaxPostRequestCompleter.future;
final Map<String, dynamic> onAjaxReadyStateChangeValue =
await onAjaxReadyStateChangeCompleter.future;
await onAjaxReadyStateChangeCompleter.future;
final Map<String, dynamic> onAjaxProgressValue =
await onAjaxProgressCompleter.future;
await onAjaxProgressCompleter.future;
expect(
mapEquals(onAjaxReadyStateChangeValue,
@ -2068,11 +2075,12 @@ void main() {
group('intercept fetch request', () {
testWidgets('send string data', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer<Map<String, dynamic>> fetchPostCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
final Completer<void> shouldInterceptFetchPostRequestCompleter =
Completer<void>();
Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
@ -2113,9 +2121,9 @@ void main() {
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
clearCache: true,
useShouldInterceptFetchRequest: true,
)),
clearCache: true,
useShouldInterceptFetchRequest: true,
)),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
@ -2147,11 +2155,12 @@ void main() {
});
testWidgets('send json data', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer<Map<String, dynamic>> fetchPostCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
final Completer<void> shouldInterceptFetchPostRequestCompleter =
Completer<void>();
Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
@ -2196,9 +2205,9 @@ void main() {
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
clearCache: true,
useShouldInterceptFetchRequest: true,
)),
clearCache: true,
useShouldInterceptFetchRequest: true,
)),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
@ -2211,7 +2220,8 @@ void main() {
},
shouldInterceptFetchRequest: (controller, fetchRequest) async {
String body = fetchRequest.body;
assert(body.contains('"firstname":"Foo"') && body.contains('"lastname":"Bar"'));
assert(body.contains('"firstname":"Foo"') &&
body.contains('"lastname":"Bar"'));
fetchRequest.body = '{"firstname": "Foo2", "lastname": "Bar2"}';
shouldInterceptFetchPostRequestCompleter.complete();
@ -2231,11 +2241,12 @@ void main() {
});
testWidgets('send URLSearchParams data', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer<Map<String, dynamic>> fetchPostCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
final Completer<void> shouldInterceptFetchPostRequestCompleter =
Completer<void>();
Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
@ -2278,9 +2289,9 @@ void main() {
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
clearCache: true,
useShouldInterceptFetchRequest: true,
)),
clearCache: true,
useShouldInterceptFetchRequest: true,
)),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
@ -2312,11 +2323,12 @@ void main() {
});
testWidgets('send FormData', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer<Map<String, dynamic>> fetchPostCompleter =
Completer<Map<String, dynamic>>();
Completer<Map<String, dynamic>>();
final Completer<void> shouldInterceptFetchPostRequestCompleter =
Completer<void>();
Completer<void>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
@ -2357,9 +2369,9 @@ void main() {
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
clearCache: true,
useShouldInterceptFetchRequest: true,
)),
clearCache: true,
useShouldInterceptFetchRequest: true,
)),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
@ -2377,7 +2389,9 @@ void main() {
var bodyString = String.fromCharCodes(body);
assert(bodyString.indexOf("WebKitFormBoundary") >= 0);
fetchRequest.body = utf8.encode(bodyString.replaceFirst("Foo", "Foo2").replaceFirst("Bar", "Bar2"));
fetchRequest.body = utf8.encode(bodyString
.replaceFirst("Foo", "Foo2")
.replaceFirst("Bar", "Bar2"));
shouldInterceptFetchPostRequestCompleter.complete();
return fetchRequest;
},
@ -2404,24 +2418,24 @@ void main() {
child: InAppWebView(
key: GlobalKey(),
initialUrlRequest:
URLRequest(url: Uri.parse('https://flutter.dev/')),
URLRequest(url: Uri.parse('https://flutter.dev/')),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
initialOptions: InAppWebViewGroupOptions(
crossPlatform:
InAppWebViewOptions(clearCache: true, contentBlockers: [
ContentBlocker(
trigger:
InAppWebViewOptions(clearCache: true, contentBlockers: [
ContentBlocker(
trigger:
ContentBlockerTrigger(urlFilter: ".*", resourceType: [
ContentBlockerTriggerResourceType.IMAGE,
ContentBlockerTriggerResourceType.STYLE_SHEET
], ifTopUrl: [
"https://flutter.dev/"
]),
action: ContentBlockerAction(
type: ContentBlockerActionType.BLOCK))
])),
ContentBlockerTriggerResourceType.IMAGE,
ContentBlockerTriggerResourceType.STYLE_SHEET
], ifTopUrl: [
"https://flutter.dev/"
]),
action: ContentBlockerAction(
type: ContentBlockerActionType.BLOCK))
])),
onLoadStop: (controller, url) {
pageLoaded.complete();
},
@ -3261,7 +3275,7 @@ setTimeout(function() {
child: InAppWebView(
key: GlobalKey(),
initialUrlRequest:
URLRequest(url: Uri.parse('https://github.com/flutter')),
URLRequest(url: Uri.parse('https://github.com/flutter')),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
@ -3278,7 +3292,7 @@ setTimeout(function() {
);
final InAppWebViewController controller =
await controllerCompleter.future;
await controllerCompleter.future;
await pageLoaded.future;
listenForScaleChange = true;
@ -4167,10 +4181,14 @@ setTimeout(function() {
await pageLoaded.future;
await controller.injectJavascriptFileFromUrl(
urlFile: Uri.parse('https://www.notawebsite..com/jquery-3.3.1.min.js'),
scriptHtmlTagAttributes: ScriptHtmlTagAttributes(id: 'jquery-error', onError: () {
jQueryLoadError.complete();
},));
urlFile:
Uri.parse('https://www.notawebsite..com/jquery-3.3.1.min.js'),
scriptHtmlTagAttributes: ScriptHtmlTagAttributes(
id: 'jquery-error',
onError: () {
jQueryLoadError.complete();
},
));
await jQueryLoadError.future;
expect(
await controller.evaluateJavascript(
@ -4182,9 +4200,12 @@ setTimeout(function() {
await controller.injectJavascriptFileFromUrl(
urlFile: Uri.parse('https://code.jquery.com/jquery-3.3.1.min.js'),
scriptHtmlTagAttributes: ScriptHtmlTagAttributes(id: 'jquery', onLoad: () {
jQueryLoaded.complete();
},));
scriptHtmlTagAttributes: ScriptHtmlTagAttributes(
id: 'jquery',
onLoad: () {
jQueryLoaded.complete();
},
));
await jQueryLoaded.future;
expect(
await controller.evaluateJavascript(
@ -4903,21 +4924,19 @@ setTimeout(function() {
expect(await InAppWebViewController.getDefaultUserAgent(), isNotNull);
});
testWidgets('launches with pull-to-refresh feature', (WidgetTester tester) async {
testWidgets('launches with pull-to-refresh feature',
(WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final pullToRefreshController = PullToRefreshController(
options: PullToRefreshOptions(
color: Colors.blue,
size: AndroidPullToRefreshSize.DEFAULT,
backgroundColor: Colors.grey,
enabled: true,
slingshotDistance: 150,
distanceToTriggerSync: 150,
attributedTitle: IOSNSAttributedString(string: "test")
),
onRefresh: () {
},
color: Colors.blue,
size: AndroidPullToRefreshSize.DEFAULT,
backgroundColor: Colors.grey,
enabled: true,
slingshotDistance: 150,
distanceToTriggerSync: 150,
attributedTitle: IOSNSAttributedString(string: "test")),
onRefresh: () {},
);
await tester.pumpWidget(
@ -4925,12 +4944,11 @@ setTimeout(function() {
textDirection: TextDirection.ltr,
child: InAppWebView(
key: GlobalKey(),
initialUrlRequest: URLRequest(url: Uri.parse('https://github.com/flutter')),
initialUrlRequest:
URLRequest(url: Uri.parse('https://github.com/flutter')),
initialOptions: InAppWebViewGroupOptions(
android: AndroidInAppWebViewOptions(
useHybridComposition: true
)
),
android:
AndroidInAppWebViewOptions(useHybridComposition: true)),
pullToRefreshController: pullToRefreshController,
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
@ -4939,22 +4957,22 @@ setTimeout(function() {
),
);
final InAppWebViewController controller =
await controllerCompleter.future;
await controllerCompleter.future;
final String? currentUrl = (await controller.getUrl())?.toString();
expect(currentUrl, 'https://github.com/flutter');
});
group('WebMessage', () {
testWidgets('WebMessageChannel', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer webMessageCompleter = Completer<String>();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: InAppWebView(
key: GlobalKey(),
initialData: InAppWebViewInitialData(
data: """
initialData: InAppWebViewInitialData(data: """
<!DOCTYPE html>
<html lang="en">
<head>
@ -4989,15 +5007,20 @@ setTimeout(function() {
webMessageCompleter.complete(consoleMessage.message);
},
onLoadStop: (controller, url) async {
var webMessageChannel = await controller.createWebMessageChannel();
var webMessageChannel =
await controller.createWebMessageChannel();
var port1 = webMessageChannel!.port1;
var port2 = webMessageChannel.port2;
await port1.setWebMessageCallback((message) async {
await port1.postMessage(WebMessage(data: message! + " and back"));
await port1
.postMessage(WebMessage(data: message! + " and back"));
});
await controller.postWebMessage(message: WebMessage(data: "capturePort", ports: [port2]), targetOrigin: Uri.parse("*"));
await controller.evaluateJavascript(source: "document.getElementById('button').click();");
await controller.postWebMessage(
message: WebMessage(data: "capturePort", ports: [port2]),
targetOrigin: Uri.parse("*"));
await controller.evaluateJavascript(
source: "document.getElementById('button').click();");
},
),
),
@ -5009,7 +5032,8 @@ setTimeout(function() {
});
testWidgets('WebMessageListener', (WidgetTester tester) async {
final Completer controllerCompleter = Completer<InAppWebViewController>();
final Completer controllerCompleter =
Completer<InAppWebViewController>();
final Completer<void> pageLoaded = Completer<void>();
final Completer webMessageCompleter = Completer<String>();
await tester.pumpWidget(
@ -5021,8 +5045,10 @@ setTimeout(function() {
await controller.addWebMessageListener(WebMessageListener(
jsObjectName: "myTestObj",
allowedOriginRules: Set.from(["https://*.example.com"]),
onPostMessage: (message, sourceOrigin, isMainFrame, replyProxy) {
assert(sourceOrigin.toString() == "https://www.example.com");
onPostMessage:
(message, sourceOrigin, isMainFrame, replyProxy) {
assert(
sourceOrigin.toString() == "https://www.example.com");
assert(isMainFrame);
replyProxy.postMessage(message! + " and back");
@ -5042,7 +5068,8 @@ setTimeout(function() {
),
);
final controller = await controllerCompleter.future;
await controller.loadUrl(urlRequest: URLRequest(url: Uri.parse("https://www.example.com/")));
await controller.loadUrl(
urlRequest: URLRequest(url: Uri.parse("https://www.example.com/")));
await pageLoaded.future;
await controller.evaluateJavascript(source: """
@ -5273,7 +5300,9 @@ setTimeout(function() {
}, skip: !Platform.isAndroid);
test('setWebContentsDebuggingEnabled', () async {
expect(AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true), completes);
expect(
AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true),
completes);
}, skip: !Platform.isAndroid);
}, skip: !Platform.isAndroid);
@ -5377,8 +5406,7 @@ setTimeout(function() {
textDirection: TextDirection.ltr,
child: InAppWebView(
key: GlobalKey(),
initialData: InAppWebViewInitialData(
data: """
initialData: InAppWebViewInitialData(data: """
<!DOCTYPE html>
<html lang="en">
<head>
@ -5393,8 +5421,7 @@ setTimeout(function() {
</script>
</body>
</html>
"""
),
"""),
initialOptions: InAppWebViewGroupOptions(
ios: IOSInAppWebViewOptions(
applePayAPIEnabled: true,
@ -5421,6 +5448,47 @@ setTimeout(function() {
}, skip: !Platform.isIOS);
});
group('Service Worker', () {
testWidgets('AndroidInAppWebViewController', (WidgetTester tester) async {
final Completer completer = Completer();
var swAvailable = await AndroidWebViewFeature.isFeatureSupported(
AndroidWebViewFeature.SERVICE_WORKER_BASIC_USAGE);
var swInterceptAvailable = await AndroidWebViewFeature.isFeatureSupported(
AndroidWebViewFeature.SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST);
if (swAvailable && swInterceptAvailable) {
AndroidServiceWorkerController serviceWorkerController =
AndroidServiceWorkerController.instance();
await serviceWorkerController
.setServiceWorkerClient(AndroidServiceWorkerClient(
shouldInterceptRequest: (request) async {
if (!completer.isCompleted) {
completer.complete();
}
return null;
},
));
} else {
completer.complete();
}
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: InAppWebView(
key: GlobalKey(),
initialUrlRequest:
URLRequest(url: Uri.parse('https://mdn.github.io/sw-test/')),
),
),
);
expect(completer.future, completes);
}, skip: !Platform.isAndroid);
});
group('Cookie Manager', () {
testWidgets('set, get, delete', (WidgetTester tester) async {
CookieManager cookieManager = CookieManager.instance();
@ -5474,7 +5542,8 @@ setTimeout(function() {
final Completer<void> pageLoaded = Completer<void>();
var headlessWebView = new HeadlessInAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse("https://github.com/flutter")),
initialUrlRequest:
URLRequest(url: Uri.parse("https://github.com/flutter")),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
@ -5503,20 +5572,20 @@ setTimeout(function() {
final Completer<void> pageLoaded = Completer<void>();
var headlessWebView = new HeadlessInAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse("https://github.com/flutter")),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
onLoadStop: (controller, url) async {
pageLoaded.complete();
}
);
initialUrlRequest:
URLRequest(url: Uri.parse("https://github.com/flutter")),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
onLoadStop: (controller, url) async {
pageLoaded.complete();
});
await headlessWebView.run();
expect(headlessWebView.isRunning(), true);
final InAppWebViewController controller =
await controllerCompleter.future;
await controllerCompleter.future;
await pageLoaded.future;
final String? url = (await controller.getUrl())?.toString();
@ -5537,11 +5606,12 @@ setTimeout(function() {
final Completer controllerCompleter = Completer<InAppWebViewController>();
var headlessWebView = new HeadlessInAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse("https://github.com/flutter")),
initialSize: Size(600, 800),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
initialUrlRequest:
URLRequest(url: Uri.parse("https://github.com/flutter")),
initialSize: Size(600, 800),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
);
await headlessWebView.run();
@ -5566,7 +5636,8 @@ setTimeout(function() {
final Completer<void> pageLoaded = Completer<void>();
var headlessWebView = new HeadlessInAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse("https://github.com/flutter")),
initialUrlRequest:
URLRequest(url: Uri.parse("https://github.com/flutter")),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(javaScriptEnabled: false)),
onWebViewCreated: (controller) {
@ -5610,8 +5681,7 @@ setTimeout(function() {
expect(inAppBrowser.isOpened(), true);
expect(() async {
await inAppBrowser.openUrlRequest(
urlRequest:
URLRequest(url: Uri.parse("https://flutter.dev")));
urlRequest: URLRequest(url: Uri.parse("https://flutter.dev")));
}, throwsA(isInstanceOf<InAppBrowserAlreadyOpenedException>()));
await inAppBrowser.firstPageLoaded.future;
@ -5633,13 +5703,14 @@ setTimeout(function() {
await inAppBrowser.show();
}, throwsA(isInstanceOf<InAppBrowserNotOpenedException>()));
await inAppBrowser.openFile(assetFilePath: "test_assets/in_app_webview_initial_file_test.html");
await inAppBrowser.openFile(
assetFilePath: "test_assets/in_app_webview_initial_file_test.html");
await inAppBrowser.browserCreated.future;
expect(inAppBrowser.isOpened(), true);
expect(() async {
await inAppBrowser.openUrlRequest(
urlRequest:
URLRequest(url: Uri.parse("https://github.com/flutter")));
URLRequest(url: Uri.parse("https://github.com/flutter")));
}, throwsA(isInstanceOf<InAppBrowserAlreadyOpenedException>()));
await inAppBrowser.firstPageLoaded.future;
@ -5661,7 +5732,8 @@ setTimeout(function() {
await inAppBrowser.show();
}, throwsA(isInstanceOf<InAppBrowserNotOpenedException>()));
await inAppBrowser.openData(data: """
await inAppBrowser.openData(
data: """
<!doctype html>
<html lang="en">
<head>
@ -5685,7 +5757,7 @@ setTimeout(function() {
expect(() async {
await inAppBrowser.openUrlRequest(
urlRequest:
URLRequest(url: Uri.parse("https://github.com/flutter")));
URLRequest(url: Uri.parse("https://github.com/flutter")));
}, throwsA(isInstanceOf<InAppBrowserAlreadyOpenedException>()));
await inAppBrowser.firstPageLoaded.future;
@ -5728,12 +5800,12 @@ setTimeout(function() {
var chromeSafariBrowser = new MyChromeSafariBrowser();
expect(chromeSafariBrowser.isOpened(), false);
await chromeSafariBrowser.open(url: Uri.parse("https://github.com/flutter"));
await chromeSafariBrowser.open(
url: Uri.parse("https://github.com/flutter"));
await chromeSafariBrowser.browserCreated.future;
expect(chromeSafariBrowser.isOpened(), true);
expect(() async {
await chromeSafariBrowser.open(
url: Uri.parse("https://flutter.dev"));
await chromeSafariBrowser.open(url: Uri.parse("https://flutter.dev"));
}, throwsA(isInstanceOf<ChromeSafariBrowserAlreadyOpenedException>()));
await expectLater(chromeSafariBrowser.firstPageLoaded.future, completes);
@ -5748,21 +5820,18 @@ setTimeout(function() {
expect(chromeSafariBrowser.isOpened(), false);
await chromeSafariBrowser.open(
url: Uri.parse("https://github.com/flutter"),
options: ChromeSafariBrowserClassOptions(
android: AndroidChromeCustomTabsOptions(
isSingleInstance: true
)
)
);
url: Uri.parse("https://github.com/flutter"),
options: ChromeSafariBrowserClassOptions(
android:
AndroidChromeCustomTabsOptions(isSingleInstance: true)));
await chromeSafariBrowser.browserCreated.future;
expect(chromeSafariBrowser.isOpened(), true);
expect(() async {
await chromeSafariBrowser.open(
url: Uri.parse("https://flutter.dev"));
await chromeSafariBrowser.open(url: Uri.parse("https://flutter.dev"));
}, throwsA(isInstanceOf<ChromeSafariBrowserAlreadyOpenedException>()));
await expectLater(chromeSafariBrowser.firstPageLoaded.future, completes);
await expectLater(
chromeSafariBrowser.firstPageLoaded.future, completes);
await chromeSafariBrowser.close();
await chromeSafariBrowser.browserClosed.future;
expect(chromeSafariBrowser.isOpened(), false);
@ -5776,18 +5845,15 @@ setTimeout(function() {
url: Uri.parse("https://github.com/flutter"),
options: ChromeSafariBrowserClassOptions(
android: AndroidChromeCustomTabsOptions(
isTrustedWebActivity: true
)
)
);
isTrustedWebActivity: true)));
await chromeSafariBrowser.browserCreated.future;
expect(chromeSafariBrowser.isOpened(), true);
expect(() async {
await chromeSafariBrowser.open(
url: Uri.parse("https://flutter.dev"));
await chromeSafariBrowser.open(url: Uri.parse("https://flutter.dev"));
}, throwsA(isInstanceOf<ChromeSafariBrowserAlreadyOpenedException>()));
await expectLater(chromeSafariBrowser.firstPageLoaded.future, completes);
await expectLater(
chromeSafariBrowser.firstPageLoaded.future, completes);
await chromeSafariBrowser.close();
await chromeSafariBrowser.browserClosed.future;
expect(chromeSafariBrowser.isOpened(), false);
@ -5801,19 +5867,15 @@ setTimeout(function() {
url: Uri.parse("https://github.com/flutter"),
options: ChromeSafariBrowserClassOptions(
android: AndroidChromeCustomTabsOptions(
isTrustedWebActivity: true,
isSingleInstance: true
)
)
);
isTrustedWebActivity: true, isSingleInstance: true)));
await chromeSafariBrowser.browserCreated.future;
expect(chromeSafariBrowser.isOpened(), true);
expect(() async {
await chromeSafariBrowser.open(
url: Uri.parse("https://flutter.dev"));
await chromeSafariBrowser.open(url: Uri.parse("https://flutter.dev"));
}, throwsA(isInstanceOf<ChromeSafariBrowserAlreadyOpenedException>()));
await expectLater(chromeSafariBrowser.firstPageLoaded.future, completes);
await expectLater(
chromeSafariBrowser.firstPageLoaded.future, completes);
await chromeSafariBrowser.close();
await chromeSafariBrowser.browserClosed.future;
expect(chromeSafariBrowser.isOpened(), false);
@ -5837,8 +5899,8 @@ setTimeout(function() {
textDirection: TextDirection.ltr,
child: InAppWebView(
key: GlobalKey(),
initialUrlRequest:
URLRequest(url: Uri.parse('http://localhost:8080/test_assets/index.html')),
initialUrlRequest: URLRequest(
url: Uri.parse('http://localhost:8080/test_assets/index.html')),
onWebViewCreated: (controller) {
controllerCompleter.complete(controller);
},
@ -5846,7 +5908,7 @@ setTimeout(function() {
),
);
final InAppWebViewController controller =
await controllerCompleter.future;
await controllerCompleter.future;
final String? currentUrl = (await controller.getUrl())?.toString();
expect(currentUrl, 'http://localhost:8080/test_assets/index.html');
});

View File

@ -71,8 +71,7 @@ class _ChromeSafariBrowserExampleScreenState
keepAliveEnabled: true,
dismissButtonStyle: DismissButtonStyle.CLOSE,
presentationStyle:
ModalPresentationStyle.OVER_FULL_SCREEN
));
ModalPresentationStyle.OVER_FULL_SCREEN));
},
child: Text("Open Chrome Safari Browser")),
));

View File

@ -83,7 +83,6 @@ class InAppBrowserExampleScreen extends StatefulWidget {
}
class _InAppBrowserExampleScreenState extends State<InAppBrowserExampleScreen> {
late PullToRefreshController pullToRefreshController;
@override
@ -99,7 +98,8 @@ class _InAppBrowserExampleScreenState extends State<InAppBrowserExampleScreen> {
widget.browser.webViewController.reload();
} else if (Platform.isIOS) {
widget.browser.webViewController.loadUrl(
urlRequest: URLRequest(url: await widget.browser.webViewController.getUrl()));
urlRequest: URLRequest(
url: await widget.browser.webViewController.getUrl()));
}
},
);
@ -121,14 +121,14 @@ class _InAppBrowserExampleScreenState extends State<InAppBrowserExampleScreen> {
ElevatedButton(
onPressed: () async {
await widget.browser.openUrlRequest(
urlRequest:
URLRequest(url: Uri.parse("https://flutter.dev")),
settings: InAppBrowserClassSettings(
webViewSettings: InAppWebViewSettings(
useShouldOverrideUrlLoading: true,
useOnLoadResource: true,
),
urlRequest:
URLRequest(url: Uri.parse("https://flutter.dev")),
settings: InAppBrowserClassSettings(
webViewSettings: InAppWebViewSettings(
useShouldOverrideUrlLoading: true,
useOnLoadResource: true,
),
),
);
},
child: Text("Open In-App Browser")),

View File

@ -1,12 +1,7 @@
import 'dart:collection';
// import 'dart:convert';
import 'dart:io';
// import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
// import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'main.dart';
@ -43,8 +38,7 @@ class _InAppWebViewExampleScreenState extends State<InAppWebViewExampleScreen> {
contextMenu = ContextMenu(
menuItems: [
ContextMenuItem(
androidId: 1,
iosId: "1",
id: 1,
title: "Special",
action: () async {
print("Menu item Special clicked!");
@ -62,11 +56,8 @@ class _InAppWebViewExampleScreenState extends State<InAppWebViewExampleScreen> {
print("onHideContextMenu");
},
onContextMenuActionItemClicked: (contextMenuItemClicked) async {
var id = (Platform.isAndroid)
? contextMenuItemClicked.androidId
: contextMenuItemClicked.iosId;
print("onContextMenuActionItemClicked: " +
id.toString() +
contextMenuItemClicked.id.toString() +
" " +
contextMenuItemClicked.title);
});
@ -76,9 +67,9 @@ class _InAppWebViewExampleScreenState extends State<InAppWebViewExampleScreen> {
color: Colors.blue,
),
onRefresh: () async {
if (Platform.isAndroid) {
if (defaultTargetPlatform == TargetPlatform.android) {
webViewController?.reload();
} else if (Platform.isIOS) {
} else if (defaultTargetPlatform == TargetPlatform.iOS) {
webViewController?.loadUrl(
urlRequest: URLRequest(url: await webViewController?.getUrl()));
}

View File

@ -31,12 +31,12 @@ Future main() async {
ServiceWorkerController serviceWorkerController =
ServiceWorkerController.instance();
serviceWorkerController.serviceWorkerClient = ServiceWorkerClient(
await serviceWorkerController.setServiceWorkerClient(ServiceWorkerClient(
shouldInterceptRequest: (request) async {
print(request);
return null;
},
);
));
}
}

View File

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

View File

@ -31,7 +31,11 @@ class CredentialDatabase: NSObject, FlutterPlugin {
switch call.method {
case "getAllAuthCredentials":
var allCredentials: [[String: Any?]] = []
for (protectionSpace, credentials) in CredentialDatabase.credentialStore!.allCredentials {
guard let credentialStore = CredentialDatabase.credentialStore else {
result(allCredentials)
return
}
for (protectionSpace, credentials) in credentialStore.allCredentials {
var crendentials: [[String: Any?]] = []
for c in credentials {
let credential: [String: Any?] = c.value.toMap()
@ -43,10 +47,17 @@ class CredentialDatabase: NSObject, FlutterPlugin {
"credentials": crendentials
]
allCredentials.append(dict)
} }
}
}
result(allCredentials)
break
case "getHttpAuthCredentials":
var crendentials: [[String: Any?]] = []
guard let credentialStore = CredentialDatabase.credentialStore else {
result(crendentials)
return
}
let host = arguments!["host"] as! String
let urlProtocol = arguments!["protocol"] as? String
let urlPort = arguments!["port"] as? Int ?? 0
@ -54,9 +65,8 @@ class CredentialDatabase: NSObject, FlutterPlugin {
if let r = realm, r.isEmpty {
realm = nil
}
var crendentials: [[String: Any?]] = []
for (protectionSpace, credentials) in CredentialDatabase.credentialStore!.allCredentials {
for (protectionSpace, credentials) in credentialStore.allCredentials {
if protectionSpace.host == host && protectionSpace.realm == realm &&
protectionSpace.protocol == urlProtocol && protectionSpace.port == urlPort {
for c in credentials {
@ -68,6 +78,11 @@ class CredentialDatabase: NSObject, FlutterPlugin {
result(crendentials)
break
case "setHttpAuthCredential":
guard let credentialStore = CredentialDatabase.credentialStore else {
result(false)
return
}
let host = arguments!["host"] as! String
let urlProtocol = arguments!["protocol"] as? String
let urlPort = arguments!["port"] as? Int ?? 0
@ -78,11 +93,17 @@ class CredentialDatabase: NSObject, FlutterPlugin {
let username = arguments!["username"] as! String
let password = arguments!["password"] as! String
let credential = URLCredential(user: username, password: password, persistence: .permanent)
CredentialDatabase.credentialStore!.set(credential,
for: URLProtectionSpace(host: host, port: urlPort, protocol: urlProtocol, realm: realm, authenticationMethod: NSURLAuthenticationMethodHTTPBasic))
credentialStore.set(credential,
for: URLProtectionSpace(host: host, port: urlPort, protocol: urlProtocol,
realm: realm, authenticationMethod: NSURLAuthenticationMethodHTTPBasic))
result(true)
break
case "removeHttpAuthCredential":
guard let credentialStore = CredentialDatabase.credentialStore else {
result(false)
return
}
let host = arguments!["host"] as! String
let urlProtocol = arguments!["protocol"] as? String
let urlPort = arguments!["port"] as? Int ?? 0
@ -96,7 +117,7 @@ class CredentialDatabase: NSObject, FlutterPlugin {
var credential: URLCredential? = nil;
var protectionSpaceCredential: URLProtectionSpace? = nil
for (protectionSpace, credentials) in CredentialDatabase.credentialStore!.allCredentials {
for (protectionSpace, credentials) in credentialStore.allCredentials {
if protectionSpace.host == host && protectionSpace.realm == realm &&
protectionSpace.protocol == urlProtocol && protectionSpace.port == urlPort {
for c in credentials {
@ -113,12 +134,17 @@ class CredentialDatabase: NSObject, FlutterPlugin {
}
if let c = credential, let protectionSpace = protectionSpaceCredential {
CredentialDatabase.credentialStore!.remove(c, for: protectionSpace)
credentialStore.remove(c, for: protectionSpace)
}
result(true)
break
case "removeHttpAuthCredentials":
guard let credentialStore = CredentialDatabase.credentialStore else {
result(false)
return
}
let host = arguments!["host"] as! String
let urlProtocol = arguments!["protocol"] as? String
let urlPort = arguments!["port"] as? Int ?? 0
@ -130,7 +156,7 @@ class CredentialDatabase: NSObject, FlutterPlugin {
var credentialsToRemove: [URLCredential] = [];
var protectionSpaceCredential: URLProtectionSpace? = nil
for (protectionSpace, credentials) in CredentialDatabase.credentialStore!.allCredentials {
for (protectionSpace, credentials) in credentialStore.allCredentials {
if protectionSpace.host == host && protectionSpace.realm == realm &&
protectionSpace.protocol == urlProtocol && protectionSpace.port == urlPort {
protectionSpaceCredential = protectionSpace
@ -145,16 +171,21 @@ class CredentialDatabase: NSObject, FlutterPlugin {
if let protectionSpace = protectionSpaceCredential {
for credential in credentialsToRemove {
CredentialDatabase.credentialStore!.remove(credential, for: protectionSpace)
credentialStore.remove(credential, for: protectionSpace)
}
}
result(true)
break
case "clearAllAuthCredentials":
for (protectionSpace, credentials) in CredentialDatabase.credentialStore!.allCredentials {
guard let credentialStore = CredentialDatabase.credentialStore else {
result(false)
return
}
for (protectionSpace, credentials) in credentialStore.allCredentials {
for credential in credentials {
CredentialDatabase.credentialStore!.remove(credential.value, for: protectionSpace)
credentialStore.remove(credential.value, for: protectionSpace)
}
}
result(true)
@ -164,4 +195,11 @@ class CredentialDatabase: NSObject, FlutterPlugin {
break
}
}
public func dispose() {
CredentialDatabase.channel?.setMethodCallHandler(nil)
CredentialDatabase.channel = nil
CredentialDatabase.registrar = nil
CredentialDatabase.credentialStore = nil
}
}

View File

@ -57,4 +57,15 @@ public class HeadlessInAppWebViewManager: NSObject, FlutterPlugin {
headlessInAppWebView.onWebViewCreated()
flutterWebView.makeInitialLoad(params: params as NSDictionary)
}
public func dispose() {
HeadlessInAppWebViewManager.channel?.setMethodCallHandler(nil)
HeadlessInAppWebViewManager.channel = nil
HeadlessInAppWebViewManager.registrar = nil
let headlessWebViews = HeadlessInAppWebViewManager.webViews.values
headlessWebViews.forEach { (headlessWebView: HeadlessInAppWebView) in
headlessWebView.dispose()
}
HeadlessInAppWebViewManager.webViews.removeAll()
}
}

View File

@ -8,13 +8,13 @@
import Foundation
@objcMembers
public class IWebViewSettings<T>: NSObject {
public class ISettings<T>: NSObject {
override init(){
super.init()
}
func parse(settings: [String: Any?]) -> IWebViewSettings {
func parse(settings: [String: Any?]) -> ISettings {
for (key, value) in settings {
if !(value is NSNull), value != nil, self.responds(to: Selector(key)) {
self.setValue(value, forKey: key)

View File

@ -140,4 +140,10 @@ public class InAppBrowserManager: NSObject, FlutterPlugin {
}
result(true)
}
public func dispose() {
InAppBrowserManager.channel?.setMethodCallHandler(nil)
InAppBrowserManager.channel = nil
InAppBrowserManager.registrar = nil
}
}

View File

@ -8,7 +8,7 @@
import Foundation
@objcMembers
public class InAppBrowserSettings: IWebViewSettings<InAppBrowserWebViewController> {
public class InAppBrowserSettings: ISettings<InAppBrowserWebViewController> {
var hidden = false
var hideToolbarTop = true

View File

@ -182,6 +182,7 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
deinit {
print("InAppBrowserWebViewController - dealloc")
dispose()
}
public override func viewDidDisappear(_ animated: Bool) {
@ -550,7 +551,10 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
}
public func dispose() {
webView.dispose()
onExit()
channel?.setMethodCallHandler(nil)
channel = nil
webView?.dispose()
webView = nil
view = nil
if previousStatusBarStyle != -1 {
@ -563,18 +567,15 @@ public class InAppBrowserWebViewController: UIViewController, InAppBrowserDelega
backButton.target = nil
reloadButton.target = nil
shareButton.target = nil
onExit()
channel?.setMethodCallHandler(nil)
channel = nil
methodCallDelegate?.webView = nil
methodCallDelegate = nil
}
public func onBrowserCreated() {
channel!.invokeMethod("onBrowserCreated", arguments: [])
channel?.invokeMethod("onBrowserCreated", arguments: [])
}
public func onExit() {
channel!.invokeMethod("onExit", arguments: [])
channel?.invokeMethod("onExit", arguments: [])
}
}

View File

@ -164,7 +164,8 @@ public class FlutterWebViewController: NSObject, FlutterPlatformView {
func dispose() {
channel?.setMethodCallHandler(nil)
methodCallDelegate?.webView = nil
channel = nil
methodCallDelegate?.dispose()
methodCallDelegate = nil
webView?.dispose()
webView = nil

View File

@ -9,7 +9,10 @@ import Flutter
import Foundation
import WebKit
public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, UIGestureRecognizerDelegate, PullToRefreshDelegate {
public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate,
WKNavigationDelegate, WKScriptMessageHandler, UIGestureRecognizerDelegate,
WKDownloadDelegate,
PullToRefreshDelegate {
var windowId: Int64?
var windowCreated = false
@ -203,13 +206,15 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
if let menu = self.contextMenu {
if let menuItems = menu["menuItems"] as? [[String : Any]] {
for menuItem in menuItems {
let id = menuItem["iosId"] as! String
let id = menuItem["id"]!
let title = menuItem["title"] as! String
let targetMethodName = "onContextMenuActionItemClicked-" + String(self.hash) + "-" + id
let targetMethodName = "onContextMenuActionItemClicked-" + String(self.hash) + "-" +
(id is Int64 ? String(id as! Int64) : id as! String)
if !self.responds(to: Selector(targetMethodName)) {
let customAction: () -> Void = {
let arguments: [String: Any?] = [
"iosId": id,
"id": id,
"iosId": id is Int64 ? String(id as! Int64) : id as! String,
"androidId": nil,
"title": title
]
@ -244,10 +249,10 @@ 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(settings: contextMenuOptionsMap)
if !action.description.starts(with: "onContextMenuActionItemClicked-") && contextMenuOptions.hideDefaultSystemContextMenuItems {
let contextMenuSettings = ContextMenuSettings()
if let contextMenuSettingsMap = menu["settings"] as? [String: Any?] {
let _ = contextMenuSettings.parse(settings: contextMenuSettingsMap)
if !action.description.starts(with: "onContextMenuActionItemClicked-") && contextMenuSettings.hideDefaultSystemContextMenuItems {
return false
}
}
@ -256,6 +261,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
if contextMenuIsShowing, !action.description.starts(with: "onContextMenuActionItemClicked-") {
let id = action.description.compactMap({ $0.asciiValue?.description }).joined()
let arguments: [String: Any?] = [
"id": id,
"iosId": id,
"androidId": nil,
"title": action.description
@ -1514,11 +1520,14 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
var action = response["action"] as? Int
action = action != nil ? action : 0;
switch action {
case 1:
decisionHandler(.grant)
break
default:
decisionHandler(.deny)
case 1:
decisionHandler(.grant)
break
case 2:
decisionHandler(.prompt)
break
default:
decisionHandler(.deny)
}
return;
}
@ -1552,11 +1561,14 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
var action = response["action"] as? Int
action = action != nil ? action : 0;
switch action {
case 1:
decisionHandler(.grant)
break
default:
decisionHandler(.deny)
case 1:
decisionHandler(.grant)
break
case 2:
decisionHandler(.prompt)
break
default:
decisionHandler(.deny)
}
return;
}
@ -1575,6 +1587,39 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
})
}
@available(iOS 14.5, *)
public func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
if let url = response.url, let useOnDownloadStart = settings?.useOnDownloadStart, useOnDownloadStart {
let downloadStartRequest = DownloadStartRequest(url: url.absoluteString,
userAgent: nil,
contentDisposition: nil,
mimeType: response.mimeType,
contentLength: response.expectedContentLength,
suggestedFilename: suggestedFilename,
textEncodingName: response.textEncodingName)
onDownloadStartRequest(request: downloadStartRequest)
}
download.delegate = nil
// cancel the download
completionHandler(nil)
}
@available(iOS 14.5, *)
public func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {
let response = navigationResponse.response
if let url = response.url, let useOnDownloadStart = settings?.useOnDownloadStart, useOnDownloadStart {
let downloadStartRequest = DownloadStartRequest(url: url.absoluteString,
userAgent: nil,
contentDisposition: nil,
mimeType: response.mimeType,
contentLength: response.expectedContentLength,
suggestedFilename: response.suggestedFilename,
textEncodingName: response.textEncodingName)
onDownloadStartRequest(request: downloadStartRequest)
}
download.delegate = nil
}
public func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
@ -1602,7 +1647,8 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
if let r = result {
response = r as! [String: Any]
let action = response["action"] as? Int
let navigationActionPolicy = WKNavigationActionPolicy.init(rawValue: action ?? WKNavigationActionPolicy.cancel.rawValue) ??
let navigationActionPolicy = WKNavigationActionPolicy
.init(rawValue: action ?? WKNavigationActionPolicy.cancel.rawValue) ??
WKNavigationActionPolicy.cancel
decisionHandler(navigationActionPolicy)
return;
@ -1644,15 +1690,11 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
var response: [String: Any]
if let r = result {
response = r as! [String: Any]
var action = response["action"] as? Int
action = action != nil ? action : 0;
switch action {
case 1:
decisionHandler(.allow)
break
default:
decisionHandler(.cancel)
}
let action = response["action"] as? Int
let navigationActionPolicy = WKNavigationResponsePolicy
.init(rawValue: action ?? WKNavigationResponsePolicy.cancel.rawValue) ??
WKNavigationResponsePolicy.cancel
decisionHandler(navigationActionPolicy)
return;
}
decisionHandler(.allow)
@ -1661,21 +1703,26 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
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/") {
let downloadStartRequest = DownloadStartRequest(url: url.absoluteString,
userAgent: nil,
contentDisposition: nil,
mimeType: mimeType,
contentLength: navigationResponse.response.expectedContentLength,
suggestedFilename: navigationResponse.response.suggestedFilename,
textEncodingName: navigationResponse.response.textEncodingName)
onDownloadStartRequest(request: downloadStartRequest)
if useOnNavigationResponse == nil || !useOnNavigationResponse! {
decisionHandler(.cancel)
if #available(iOS 14.5, *), !navigationResponse.canShowMIMEType {
decisionHandler(.download)
return
} else {
let mimeType = navigationResponse.response.mimeType
if let url = navigationResponse.response.url, navigationResponse.isForMainFrame {
if url.scheme != "file", mimeType != nil, !mimeType!.starts(with: "text/") {
let downloadStartRequest = DownloadStartRequest(url: url.absoluteString,
userAgent: nil,
contentDisposition: nil,
mimeType: mimeType,
contentLength: navigationResponse.response.expectedContentLength,
suggestedFilename: navigationResponse.response.suggestedFilename,
textEncodingName: navigationResponse.response.textEncodingName)
onDownloadStartRequest(request: downloadStartRequest)
if useOnNavigationResponse == nil || !useOnNavigationResponse! {
decisionHandler(.cancel)
}
return
}
return
}
}
}
@ -1791,8 +1838,8 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
completionHandler(.useCredential, credential)
break
case 2:
if InAppWebView.credentialsProposed.count == 0 {
for (protectionSpace, credentials) in CredentialDatabase.credentialStore!.allCredentials {
if InAppWebView.credentialsProposed.count == 0, let credentialStore = CredentialDatabase.credentialStore {
for (protectionSpace, credentials) in credentialStore.allCredentials {
if protectionSpace.host == host && protectionSpace.realm == realm &&
protectionSpace.protocol == prot && protectionSpace.port == port {
for credential in credentials {
@ -3023,6 +3070,12 @@ if(window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)] != null) {
}
public func dispose() {
channel = nil
removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
removeObserver(self, forKeyPath: #keyPath(WKWebView.url))
removeObserver(self, forKeyPath: #keyPath(WKWebView.title))
scrollView.removeObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset))
scrollView.removeObserver(self, forKeyPath: #keyPath(UIScrollView.zoomScale))
resumeTimers()
stopLoading()
disposeWebMessageChannels()
@ -3043,15 +3096,10 @@ if(window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)] != null) {
InAppWebView.windowWebViews.removeValue(forKey: wId)
}
configuration.userContentController.dispose(windowId: windowId)
removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
removeObserver(self, forKeyPath: #keyPath(WKWebView.url))
removeObserver(self, forKeyPath: #keyPath(WKWebView.title))
NotificationCenter.default.removeObserver(self)
for imp in customIMPs {
imp_removeBlock(imp)
}
scrollView.removeObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset))
scrollView.removeObserver(self, forKeyPath: #keyPath(UIScrollView.zoomScale))
longPressRecognizer.removeTarget(self, action: #selector(longPressGestureDetected))
longPressRecognizer.delegate = nil
scrollView.removeGestureRecognizer(longPressRecognizer)
@ -3068,7 +3116,6 @@ if(window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)] != null) {
navigationDelegate = nil
scrollView.delegate = nil
isPausedTimersCompletionHandler = nil
channel = nil
SharedLastTouchPointTimestamp.removeValue(forKey: self)
callAsyncJavaScriptBelowIOS14Results.removeAll()
super.removeFromSuperview()

View File

@ -9,7 +9,7 @@ import Foundation
import WebKit
@objcMembers
public class InAppWebViewSettings: IWebViewSettings<InAppWebView> {
public class InAppWebViewSettings: ISettings<InAppWebView> {
var useShouldOverrideUrlLoading = false
var useOnLoadResource = false

View File

@ -598,8 +598,12 @@ public class InAppWebViewMethodHandler: FlutterMethodCallDelegate {
}
}
deinit {
print("InAppWebViewMethodHandler - dealloc")
public func dispose() {
webView = nil
}
deinit {
print("InAppWebViewMethodHandler - dealloc")
dispose()
}
}

View File

@ -72,4 +72,12 @@ class InAppWebViewStatic: NSObject, FlutterPlugin {
completionHandler(defaultUserAgent)
}
}
public func dispose() {
InAppWebViewStatic.channel?.setMethodCallHandler(nil)
InAppWebViewStatic.channel = nil
InAppWebViewStatic.registrar = nil
InAppWebViewStatic.webViewForUserAgent = nil
InAppWebViewStatic.defaultUserAgent = nil
}
}

View File

@ -100,6 +100,11 @@ class MyCookieManager: NSObject, FlutterPlugin {
isHttpOnly: Bool?,
sameSite: String?,
result: @escaping FlutterResult) {
guard let httpCookieStore = MyCookieManager.httpCookieStore else {
result(false)
return
}
var properties: [HTTPCookiePropertyKey: Any] = [:]
properties[.originURL] = url
properties[.name] = name
@ -138,7 +143,7 @@ class MyCookieManager: NSObject, FlutterPlugin {
let cookie = HTTPCookie(properties: properties)!
MyCookieManager.httpCookieStore!.setCookie(cookie, completionHandler: {() in
httpCookieStore.setCookie(cookie, completionHandler: {() in
result(true)
})
}
@ -146,8 +151,13 @@ class MyCookieManager: NSObject, FlutterPlugin {
public static func getCookies(url: String, result: @escaping FlutterResult) {
var cookieList: [[String: Any?]] = []
guard let httpCookieStore = MyCookieManager.httpCookieStore else {
result(cookieList)
return
}
if let urlHost = URL(string: url)?.host {
MyCookieManager.httpCookieStore!.getAllCookies { (cookies) in
httpCookieStore.getAllCookies { (cookies) in
for cookie in cookies {
if urlHost.hasSuffix(cookie.domain) || ".\(urlHost)".hasSuffix(cookie.domain) {
var sameSite: String? = nil
@ -189,7 +199,12 @@ class MyCookieManager: NSObject, FlutterPlugin {
public static func getAllCookies(result: @escaping FlutterResult) {
var cookieList: [[String: Any?]] = []
MyCookieManager.httpCookieStore!.getAllCookies { (cookies) in
guard let httpCookieStore = MyCookieManager.httpCookieStore else {
result(cookieList)
return
}
httpCookieStore.getAllCookies { (cookies) in
for cookie in cookies {
var sameSite: String? = nil
if #available(iOS 13.0, *) {
@ -221,7 +236,12 @@ class MyCookieManager: NSObject, FlutterPlugin {
}
public static func deleteCookie(url: String, name: String, domain: String, path: String, result: @escaping FlutterResult) {
MyCookieManager.httpCookieStore!.getAllCookies { (cookies) in
guard let httpCookieStore = MyCookieManager.httpCookieStore else {
result(false)
return
}
httpCookieStore.getAllCookies { (cookies) in
for cookie in cookies {
var originURL = ""
if cookie.properties![.originURL] is String {
@ -234,7 +254,7 @@ class MyCookieManager: NSObject, FlutterPlugin {
continue
}
if (cookie.domain == domain || cookie.domain == ".\(domain)" || ".\(cookie.domain)" == domain) && cookie.name == name && cookie.path == path {
MyCookieManager.httpCookieStore!.delete(cookie, completionHandler: {
httpCookieStore.delete(cookie, completionHandler: {
result(true)
})
return
@ -245,7 +265,12 @@ class MyCookieManager: NSObject, FlutterPlugin {
}
public static func deleteCookies(url: String, domain: String, path: String, result: @escaping FlutterResult) {
MyCookieManager.httpCookieStore!.getAllCookies { (cookies) in
guard let httpCookieStore = MyCookieManager.httpCookieStore else {
result(false)
return
}
httpCookieStore.getAllCookies { (cookies) in
for cookie in cookies {
var originURL = ""
if cookie.properties![.originURL] is String {
@ -258,7 +283,7 @@ class MyCookieManager: NSObject, FlutterPlugin {
continue
}
if (cookie.domain == domain || cookie.domain == ".\(domain)" || ".\(cookie.domain)" == domain) && cookie.path == path {
MyCookieManager.httpCookieStore!.delete(cookie, completionHandler: nil)
httpCookieStore.delete(cookie, completionHandler: nil)
}
}
result(true)
@ -272,4 +297,11 @@ class MyCookieManager: NSObject, FlutterPlugin {
result(true)
})
}
public func dispose() {
MyCookieManager.channel?.setMethodCallHandler(nil)
MyCookieManager.channel = nil
MyCookieManager.registrar = nil
MyCookieManager.httpCookieStore = nil
}
}

View File

@ -53,7 +53,13 @@ class MyWebStorageManager: NSObject, FlutterPlugin {
public static func fetchDataRecords(dataTypes: Set<String>, result: @escaping FlutterResult) {
var recordList: [[String: Any?]] = []
MyWebStorageManager.websiteDataStore!.fetchDataRecords(ofTypes: dataTypes) { (data) in
guard let websiteDataStore = MyWebStorageManager.websiteDataStore else {
result(recordList)
return
}
websiteDataStore.fetchDataRecords(ofTypes: dataTypes) { (data) in
for record in data {
recordList.append([
"displayName": record.displayName,
@ -68,7 +74,13 @@ class MyWebStorageManager: NSObject, FlutterPlugin {
public static func removeDataFor(dataTypes: Set<String>, recordList: [[String: Any?]], result: @escaping FlutterResult) {
var records: [WKWebsiteDataRecord] = []
MyWebStorageManager.websiteDataStore!.fetchDataRecords(ofTypes: dataTypes) { (data) in
guard let websiteDataStore = MyWebStorageManager.websiteDataStore else {
result(false)
return
}
websiteDataStore.fetchDataRecords(ofTypes: dataTypes) { (data) in
for record in data {
for r in recordList {
let displayName = r["displayName"] as! String
@ -78,16 +90,28 @@ class MyWebStorageManager: NSObject, FlutterPlugin {
}
}
}
MyWebStorageManager.websiteDataStore!.removeData(ofTypes: dataTypes, for: records) {
websiteDataStore.removeData(ofTypes: dataTypes, for: records) {
result(true)
}
}
}
public static func removeDataModifiedSince(dataTypes: Set<String>, timestamp: Int64, result: @escaping FlutterResult) {
guard let websiteDataStore = MyWebStorageManager.websiteDataStore else {
result(false)
return
}
let date = NSDate(timeIntervalSince1970: TimeInterval(timestamp))
MyWebStorageManager.websiteDataStore!.removeData(ofTypes: dataTypes, modifiedSince: date as Date) {
websiteDataStore.removeData(ofTypes: dataTypes, modifiedSince: date as Date) {
result(true)
}
}
public func dispose() {
MyWebStorageManager.channel?.setMethodCallHandler(nil)
MyWebStorageManager.channel = nil
MyWebStorageManager.registrar = nil
MyWebStorageManager.websiteDataStore = nil
}
}

View File

@ -60,4 +60,10 @@ class PlatformUtil: NSObject, FlutterPlugin {
formatter.timeZone = timezone
return formatter.string(from: PlatformUtil.getDateFromMilliseconds(date: date))
}
public func dispose() {
PlatformUtil.channel?.setMethodCallHandler(nil)
PlatformUtil.channel = nil
PlatformUtil.registrar = nil
}
}

View File

@ -109,5 +109,6 @@ public class PullToRefreshControl : UIRefreshControl, FlutterPlugin {
deinit {
print("PullToRefreshControl - dealloc")
dispose()
}
}

View File

@ -7,7 +7,7 @@
import Foundation
public class PullToRefreshSettings : IWebViewSettings<PullToRefreshControl> {
public class PullToRefreshSettings : ISettings<PullToRefreshControl> {
var enabled = true
var color: String?

View File

@ -91,4 +91,10 @@ public class ChromeSafariBrowserManager: NSObject, FlutterPlugin {
result(FlutterError.init(code: "ChromeSafariBrowserManager", message: "SafariViewController is not available!", details: nil))
}
public func dispose() {
ChromeSafariBrowserManager.channel?.setMethodCallHandler(nil)
ChromeSafariBrowserManager.channel = nil
ChromeSafariBrowserManager.registrar = nil
}
}

View File

@ -9,7 +9,7 @@ import Foundation
@available(iOS 9.0, *)
@objcMembers
public class SafariBrowserSettings: IWebViewSettings<SafariViewController> {
public class SafariBrowserSettings: ISettings<SafariViewController> {
var entersReaderIfAvailable = false
var barCollapsingEnabled = false

View File

@ -22,6 +22,7 @@ public class SafariViewController: SFSafariViewController, FlutterPlugin, SFSafa
deinit {
print("SafariViewController - dealloc")
dispose()
}
public func prepareMethodChannel() {
@ -123,20 +124,21 @@ public class SafariViewController: SFSafariViewController, FlutterPlugin, SFSafa
// }
public func onChromeSafariBrowserOpened() {
channel!.invokeMethod("onChromeSafariBrowserOpened", arguments: [])
channel?.invokeMethod("onChromeSafariBrowserOpened", arguments: [])
}
public func onChromeSafariBrowserCompletedInitialLoad() {
channel!.invokeMethod("onChromeSafariBrowserCompletedInitialLoad", arguments: [])
channel?.invokeMethod("onChromeSafariBrowserCompletedInitialLoad", arguments: [])
}
public func onChromeSafariBrowserClosed() {
channel!.invokeMethod("onChromeSafariBrowserClosed", arguments: [])
channel?.invokeMethod("onChromeSafariBrowserClosed", arguments: [])
}
public func dispose() {
channel?.setMethodCallHandler(nil)
channel = nil
delegate = nil
channel!.setMethodCallHandler(nil)
}
}
@ -180,7 +182,12 @@ class CustomUIActivity : UIActivity {
}
override func perform() {
let channel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_chromesafaribrowser_" + viewId, binaryMessenger: SwiftFlutterPlugin.instance!.registrar!.messenger())
guard let registrar = SwiftFlutterPlugin.instance?.registrar else {
return
}
let channel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_chromesafaribrowser_" + viewId,
binaryMessenger: registrar.messenger())
let arguments: [String: Any?] = [
"url": url.absoluteString,

View File

@ -49,16 +49,39 @@ public class SwiftFlutterPlugin: NSObject, FlutterPlugin {
headlessInAppWebViewManager = HeadlessInAppWebViewManager(registrar: registrar)
chromeSafariBrowserManager = ChromeSafariBrowserManager(registrar: registrar)
inAppWebViewStatic = InAppWebViewStatic(registrar: registrar)
credentialDatabase = CredentialDatabase(registrar: registrar)
if #available(iOS 11.0, *) {
myCookieManager = MyCookieManager(registrar: registrar)
}
if #available(iOS 9.0, *) {
myWebStorageManager = MyWebStorageManager(registrar: registrar)
}
credentialDatabase = CredentialDatabase(registrar: registrar)
}
public static func register(with registrar: FlutterPluginRegistrar) {
SwiftFlutterPlugin.instance = SwiftFlutterPlugin(with: registrar)
}
public func detachFromEngine(for registrar: FlutterPluginRegistrar) {
platformUtil?.dispose()
platformUtil = nil
inAppBrowserManager?.dispose()
inAppBrowserManager = nil
headlessInAppWebViewManager?.dispose()
headlessInAppWebViewManager = nil
chromeSafariBrowserManager?.dispose()
chromeSafariBrowserManager = nil
inAppWebViewStatic?.dispose()
inAppWebViewStatic = nil
credentialDatabase?.dispose()
credentialDatabase = nil
if #available(iOS 11.0, *) {
(myCookieManager as! MyCookieManager?)?.dispose()
myCookieManager = nil
}
if #available(iOS 9.0, *) {
(myWebStorageManager as! MyWebStorageManager?)?.dispose()
myWebStorageManager = nil
}
}
}

View File

@ -10,6 +10,10 @@ import WebKit
extension WKNavigationAction {
public func toMap () -> [String:Any?] {
var shouldPerformDownload: Bool? = nil
if #available(iOS 14.5, *) {
shouldPerformDownload = self.shouldPerformDownload
}
return [
"request": request.toMap(),
"isForMainFrame": targetFrame?.isMainFrame ?? false,
@ -17,7 +21,8 @@ extension WKNavigationAction {
"isRedirect": nil,
"navigationType": navigationType.rawValue,
"sourceFrame": sourceFrame.toMap(),
"targetFrame": targetFrame?.toMap()
"targetFrame": targetFrame?.toMap(),
"shouldPerformDownload": shouldPerformDownload
]
}
}

View File

@ -21,7 +21,7 @@ extension WKUserContentController {
var contentWorlds: Set<WKContentWorld> {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return WKUserContentController._contentWorlds[tmpAddress]!
return WKUserContentController._contentWorlds[tmpAddress] ?? []
}
set(newValue) {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
@ -33,7 +33,7 @@ extension WKUserContentController {
var userOnlyScripts: [WKUserScriptInjectionTime:OrderedSet<UserScript>] {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return WKUserContentController._userOnlyScripts[tmpAddress]!
return WKUserContentController._userOnlyScripts[tmpAddress] ?? [:]
}
set(newValue) {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
@ -45,7 +45,7 @@ extension WKUserContentController {
var pluginScripts: [WKUserScriptInjectionTime:OrderedSet<PluginScript>] {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return WKUserContentController._pluginScripts[tmpAddress]!
return WKUserContentController._pluginScripts[tmpAddress] ?? [:]
}
set(newValue) {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))

View File

@ -23,5 +23,6 @@ public class WebMessage : NSObject {
deinit {
print("WebMessage - dealloc")
dispose()
}
}

View File

@ -126,6 +126,7 @@ public class WebMessageChannel : FlutterMethodCallDelegate {
public func dispose() {
channel?.setMethodCallHandler(nil)
channel = nil
for port in ports {
port.dispose()
}
@ -140,11 +141,11 @@ public class WebMessageChannel : FlutterMethodCallDelegate {
}
})();
""")
channel = nil
webView = nil
}
deinit {
print("WebMessageChannel - dealloc")
dispose()
}
}

View File

@ -222,5 +222,6 @@ public class WebMessageListener : FlutterMethodCallDelegate {
deinit {
print("WebMessageListener - dealloc")
dispose()
}
}

View File

@ -118,5 +118,6 @@ public class WebMessagePort : NSObject {
deinit {
print("WebMessagePort - dealloc")
dispose()
}
}

View File

@ -12,7 +12,7 @@ var SharedLastTouchPointTimestamp: [InAppWebView: Int64] = [:]
public class Util {
public static func getUrlAsset(assetFilePath: String) throws -> URL {
let key = SwiftFlutterPlugin.instance!.registrar!.lookupKey(forAsset: assetFilePath)
let key = SwiftFlutterPlugin.instance?.registrar?.lookupKey(forAsset: assetFilePath)
guard let assetURL = Bundle.main.url(forResource: key, withExtension: nil) else {
throw NSError(domain: assetFilePath + " asset file cannot be found!", code: 0)
}
@ -20,7 +20,7 @@ public class Util {
}
public static func getAbsPathAsset(assetFilePath: String) throws -> String {
let key = SwiftFlutterPlugin.instance!.registrar!.lookupKey(forAsset: assetFilePath)
let key = SwiftFlutterPlugin.instance?.registrar?.lookupKey(forAsset: assetFilePath)
guard let assetAbsPath = Bundle.main.path(forResource: key, ofType: nil) else {
throw NSError(domain: assetFilePath + " asset file cannot be found!", code: 0)
}

View File

@ -14,13 +14,23 @@ class ServiceWorkerController {
static const MethodChannel _channel = const MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_serviceworkercontroller');
ServiceWorkerClient? serviceWorkerClient;
///Gets the [ServiceWorkerController] shared instance.
static ServiceWorkerController instance() {
return (_instance != null) ? _instance! : _init();
}
ServiceWorkerClient? _serviceWorkerClient;
ServiceWorkerClient? get serviceWorkerClient => _serviceWorkerClient;
///Sets the service worker client
setServiceWorkerClient(ServiceWorkerClient? value) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('isNull', () => value == null);
await _channel.invokeMethod("setServiceWorkerClient", args);
_serviceWorkerClient = value;
}
static ServiceWorkerController _init() {
_channel.setMethodCallHandler(_handleMethod);
_instance = ServiceWorkerController();
@ -180,7 +190,25 @@ class AndroidServiceWorkerController {
static const MethodChannel _channel = const MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_serviceworkercontroller');
AndroidServiceWorkerClient? serviceWorkerClient;
AndroidServiceWorkerClient? _serviceWorkerClient;
AndroidServiceWorkerClient? get serviceWorkerClient => _serviceWorkerClient;
@Deprecated("Use setServiceWorkerClient instead")
set serviceWorkerClient(AndroidServiceWorkerClient? value) {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('isNull', () => value == null);
_channel.invokeMethod("setServiceWorkerClient", args);
_serviceWorkerClient = value;
}
///Sets the service worker client
setServiceWorkerClient(AndroidServiceWorkerClient? value) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('isNull', () => value == null);
await _channel.invokeMethod("setServiceWorkerClient", args);
_serviceWorkerClient = value;
}
///Gets the [AndroidServiceWorkerController] shared instance.
static AndroidServiceWorkerController instance() {

View File

@ -241,8 +241,8 @@ class ChromeSafariBrowserSettings implements ChromeSafariBrowserOptions {
settings.additionalTrustedOrigins = map["additionalTrustedOrigins"];
switch (map["displayMode"]["type"]) {
case "IMMERSIVE_MODE":
settings.displayMode =
TrustedWebActivityImmersiveDisplayMode.fromMap(map["displayMode"]);
settings.displayMode = TrustedWebActivityImmersiveDisplayMode.fromMap(
map["displayMode"]);
break;
case "DEFAULT_MODE":
default:
@ -255,15 +255,15 @@ class ChromeSafariBrowserSettings implements ChromeSafariBrowserOptions {
settings.entersReaderIfAvailable = map["entersReaderIfAvailable"];
settings.barCollapsingEnabled = map["barCollapsingEnabled"];
settings.dismissButtonStyle =
DismissButtonStyle.fromValue(map["dismissButtonStyle"])!;
DismissButtonStyle.fromValue(map["dismissButtonStyle"])!;
settings.preferredBarTintColor =
UtilColor.fromHex(map["preferredBarTintColor"]);
settings.preferredControlTintColor =
UtilColor.fromHex(map["preferredControlTintColor"]);
settings.presentationStyle =
ModalPresentationStyle.fromValue(map["presentationStyle"])!;
ModalPresentationStyle.fromValue(map["presentationStyle"])!;
settings.transitionStyle =
ModalTransitionStyle.fromValue(map["transitionStyle"])!;
ModalTransitionStyle.fromValue(map["transitionStyle"])!;
}
return settings;
}

View File

@ -1,3 +1,5 @@
import 'package:flutter/foundation.dart';
import 'in_app_webview/webview.dart';
import 'types.dart';
@ -20,9 +22,13 @@ class ContextMenu {
final void Function(ContextMenuItem contextMenuItemClicked)?
onContextMenuActionItemClicked;
///Context menu options.
///Use [settings] instead
@Deprecated("Use settings instead")
final ContextMenuOptions? options;
///Context menu settings.
final ContextMenuSettings? settings;
///List of the custom [ContextMenuItem].
final List<ContextMenuItem> menuItems;
@ -31,12 +37,14 @@ class ContextMenu {
this.onCreateContextMenu,
this.onHideContextMenu,
this.options,
this.settings,
this.onContextMenuActionItemClicked});
Map<String, dynamic> toMap() {
return {
"menuItems": menuItems.map((menuItem) => menuItem.toMap()).toList(),
"options": options?.toMap()
// ignore: deprecated_member_use_from_same_package
"settings": settings?.toMap() ?? options?.toMap()
};
}
@ -52,12 +60,19 @@ class ContextMenu {
///Class that represent an item of the [ContextMenu].
class ContextMenuItem {
///Android menu item ID.
///Use [id] instead.
@Deprecated("Use id instead")
int? androidId;
///iOS menu item ID.
///Use [id] instead.
@Deprecated("Use id instead")
String? iosId;
///Menu item ID. It cannot be `null` and it can be a [String] or an [int].
///
///**NOTE for Android**: it must be an [int] value.
dynamic id;
///Menu item title.
String title;
@ -65,10 +80,31 @@ class ContextMenuItem {
Function()? action;
ContextMenuItem(
{this.androidId, this.iosId, required this.title, this.action});
{this.id,
this.androidId,
this.iosId,
required this.title,
this.action}) {
if (defaultTargetPlatform == TargetPlatform.android) {
// ignore: deprecated_member_use_from_same_package
this.id = this.id ?? this.androidId;
assert(this.id is int);
} else if (defaultTargetPlatform == TargetPlatform.iOS) {
// ignore: deprecated_member_use_from_same_package
this.id = this.id ?? this.iosId;
}
assert(this.id != null && (this.id is int || this.id is String));
}
Map<String, dynamic> toMap() {
return {"androidId": androidId, "iosId": iosId, "title": title};
return {
"id": id,
// ignore: deprecated_member_use_from_same_package
"androidId": androidId,
// ignore: deprecated_member_use_from_same_package
"iosId": iosId,
"title": title
};
}
Map<String, dynamic> toJson() {
@ -81,7 +117,31 @@ class ContextMenuItem {
}
}
///Class that represents available options used by [ContextMenu].
///Class that represents available settings used by [ContextMenu].
class ContextMenuSettings {
///Whether all the default system context menu items should be hidden or not. The default value is `false`.
bool hideDefaultSystemContextMenuItems;
ContextMenuSettings({this.hideDefaultSystemContextMenuItems = false});
Map<String, dynamic> toMap() {
return {
"hideDefaultSystemContextMenuItems": hideDefaultSystemContextMenuItems
};
}
Map<String, dynamic> toJson() {
return this.toMap();
}
@override
String toString() {
return toMap().toString();
}
}
///Use [ContextMenuSettings] instead.
@Deprecated("Use ContextMenuSettings instead")
class ContextMenuOptions {
///Whether all the default system context menu items should be hidden or not. The default value is `false`.
bool hideDefaultSystemContextMenuItems;

View File

@ -286,7 +286,7 @@ class InAppBrowserSettings
settings.closeOnCannotGoBack = map["closeOnCannotGoBack"];
settings.allowGoBackWithBackButton = map["allowGoBackWithBackButton"];
settings.shouldCloseOnBackButtonPressed =
map["shouldCloseOnBackButtonPressed"];
map["shouldCloseOnBackButtonPressed"];
}
if (defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS) {
settings.toolbarTopTranslucent = map["toolbarTopTranslucent"];
@ -301,9 +301,9 @@ class InAppBrowserSettings
settings.closeButtonCaption = map["closeButtonCaption"];
settings.closeButtonColor = UtilColor.fromHex(map["closeButtonColor"]);
settings.presentationStyle =
ModalPresentationStyle.fromValue(map["presentationStyle"])!;
ModalPresentationStyle.fromValue(map["presentationStyle"])!;
settings.transitionStyle =
ModalTransitionStyle.fromValue(map["transitionStyle"])!;
ModalTransitionStyle.fromValue(map["transitionStyle"])!;
}
return settings;
}

View File

@ -107,7 +107,8 @@ abstract class AppleInAppWebViewControllerMixin {
///- iOS ([Official API - WKWebView.requestMediaPlaybackState](https://developer.apple.com/documentation/webkit/wkwebview/3752241-requestmediaplaybackstate)).
Future<MediaPlaybackState?> requestMediaPlaybackState() async {
Map<String, dynamic> args = <String, dynamic>{};
return MediaPlaybackState.fromValue(await _channel.invokeMethod('requestMediaPlaybackState', args));
return MediaPlaybackState.fromValue(
await _channel.invokeMethod('requestMediaPlaybackState', args));
}
}

View File

@ -472,8 +472,7 @@ class InAppWebView extends StatefulWidget implements WebView {
NavigationResponse navigationResponse)? onNavigationResponse;
@override
final Future<PermissionResponse?> Function(
InAppWebViewController controller,
final Future<PermissionResponse?> Function(InAppWebViewController controller,
PermissionRequest permissionRequest)? onPermissionRequest;
@override

View File

@ -731,9 +731,9 @@ class InAppWebViewController
List<String> resources = call.arguments["resources"].cast<String>();
Map<String, dynamic> arguments =
call.arguments.cast<String, dynamic>();
call.arguments.cast<String, dynamic>();
PermissionRequest permissionRequest =
PermissionRequest.fromMap(arguments)!;
PermissionRequest.fromMap(arguments)!;
if (_webview != null) {
if (_webview!.onPermissionRequest != null)
@ -747,11 +747,12 @@ class InAppWebViewController
?.toMap();
}
} else {
return (await _inAppBrowser!
.onPermissionRequest(permissionRequest))?.toMap() ??
(await _inAppBrowser!
return (await _inAppBrowser!.onPermissionRequest(permissionRequest))
?.toMap() ??
(await _inAppBrowser!
// ignore: deprecated_member_use_from_same_package
.androidOnPermissionRequest(origin, resources))?.toMap();
.androidOnPermissionRequest(origin, resources))
?.toMap();
}
}
break;
@ -944,16 +945,18 @@ class InAppWebViewController
if (contextMenu != null) {
int? androidId = call.arguments["androidId"];
String? iosId = call.arguments["iosId"];
dynamic id = call.arguments["id"];
String title = call.arguments["title"];
ContextMenuItem menuItemClicked = ContextMenuItem(
androidId: androidId, iosId: iosId, title: title, action: null);
id: id,
androidId: androidId,
iosId: iosId,
title: title,
action: null);
for (var menuItem in contextMenu.menuItems) {
if ((defaultTargetPlatform == TargetPlatform.android &&
menuItem.androidId == androidId) ||
(defaultTargetPlatform == TargetPlatform.iOS &&
menuItem.iosId == iosId)) {
if (menuItem.id == id) {
menuItemClicked = menuItem;
if (menuItem.action != null) {
menuItem.action!();
@ -1864,7 +1867,8 @@ class InAppWebViewController
///Use [setSettings] instead.
@Deprecated('Use setSettings instead')
Future<void> setOptions({required InAppWebViewGroupOptions options}) async {
InAppWebViewSettings settings = InAppWebViewSettings.fromMap(options.toMap());
InAppWebViewSettings settings =
InAppWebViewSettings.fromMap(options.toMap());
await setSettings(settings: settings);
}
@ -2325,7 +2329,8 @@ class InAppWebViewController
try {
Map<String, dynamic> args = <String, dynamic>{};
themeColor = UtilColor.fromStringRepresentation(await _channel.invokeMethod('getMetaThemeColor', args));
themeColor = UtilColor.fromStringRepresentation(
await _channel.invokeMethod('getMetaThemeColor', args));
} catch (e) {
// not implemented
}

View File

@ -1414,7 +1414,7 @@ class InAppWebViewSettings
settings.hardwareAcceleration = map["hardwareAcceleration"];
settings.supportMultipleWindows = map["supportMultipleWindows"];
settings.regexToCancelSubFramesLoading =
map["regexToCancelSubFramesLoading"];
map["regexToCancelSubFramesLoading"];
settings.useHybridComposition = map["useHybridComposition"];
settings.useShouldInterceptRequest = map["useShouldInterceptRequest"];
settings.useOnRenderProcessGone = map["useOnRenderProcessGone"];
@ -1424,7 +1424,7 @@ class InAppWebViewSettings
settings.verticalScrollbarPosition =
VerticalScrollbarPosition.fromValue(map["verticalScrollbarPosition"]);
settings.scrollBarDefaultDelayBeforeFade =
map["scrollBarDefaultDelayBeforeFade"];
map["scrollBarDefaultDelayBeforeFade"];
settings.scrollbarFadingEnabled = map["scrollbarFadingEnabled"];
settings.scrollBarFadeDuration = map["scrollBarFadeDuration"];
settings.rendererPriorityPolicy = RendererPriorityPolicy.fromMap(
@ -1443,28 +1443,28 @@ class InAppWebViewSettings
settings.disallowOverScroll = map["disallowOverScroll"];
settings.enableViewportScale = map["enableViewportScale"];
settings.suppressesIncrementalRendering =
map["suppressesIncrementalRendering"];
map["suppressesIncrementalRendering"];
settings.allowsAirPlayForMediaPlayback =
map["allowsAirPlayForMediaPlayback"];
map["allowsAirPlayForMediaPlayback"];
settings.allowsBackForwardNavigationGestures =
map["allowsBackForwardNavigationGestures"];
map["allowsBackForwardNavigationGestures"];
settings.allowsLinkPreview = map["allowsLinkPreview"];
settings.ignoresViewportScaleLimits = map["ignoresViewportScaleLimits"];
settings.allowsInlineMediaPlayback = map["allowsInlineMediaPlayback"];
settings.allowsPictureInPictureMediaPlayback =
map["allowsPictureInPictureMediaPlayback"];
map["allowsPictureInPictureMediaPlayback"];
settings.isFraudulentWebsiteWarningEnabled =
map["isFraudulentWebsiteWarningEnabled"];
map["isFraudulentWebsiteWarningEnabled"];
settings.selectionGranularity =
SelectionGranularity.fromValue(map["selectionGranularity"])!;
SelectionGranularity.fromValue(map["selectionGranularity"])!;
settings.dataDetectorTypes = dataDetectorTypes;
settings.sharedCookiesEnabled = map["sharedCookiesEnabled"];
settings.automaticallyAdjustsScrollIndicatorInsets =
map["automaticallyAdjustsScrollIndicatorInsets"];
map["automaticallyAdjustsScrollIndicatorInsets"];
settings.accessibilityIgnoresInvertColors =
map["accessibilityIgnoresInvertColors"];
map["accessibilityIgnoresInvertColors"];
settings.decelerationRate =
ScrollViewDecelerationRate.fromValue(map["decelerationRate"])!;
ScrollViewDecelerationRate.fromValue(map["decelerationRate"])!;
settings.alwaysBounceVertical = map["alwaysBounceVertical"];
settings.alwaysBounceHorizontal = map["alwaysBounceHorizontal"];
settings.scrollsToTop = map["scrollsToTop"];
@ -1472,24 +1472,26 @@ class InAppWebViewSettings
settings.maximumZoomScale = map["maximumZoomScale"];
settings.minimumZoomScale = map["minimumZoomScale"];
settings.contentInsetAdjustmentBehavior =
ScrollViewContentInsetAdjustmentBehavior.fromValue(
map["contentInsetAdjustmentBehavior"])!;
ScrollViewContentInsetAdjustmentBehavior.fromValue(
map["contentInsetAdjustmentBehavior"])!;
settings.isDirectionalLockEnabled = map["isDirectionalLockEnabled"];
settings.mediaType = map["mediaType"];
settings.pageZoom = map["pageZoom"];
settings.limitsNavigationsToAppBoundDomains =
map["limitsNavigationsToAppBoundDomains"];
map["limitsNavigationsToAppBoundDomains"];
settings.useOnNavigationResponse = map["useOnNavigationResponse"];
settings.applePayAPIEnabled = map["applePayAPIEnabled"];
settings.allowingReadAccessTo = map["allowingReadAccessTo"] != null
? Uri.parse(map["allowingReadAccessTo"])
: null;
settings.disableLongPressContextMenuOnLinks =
map["disableLongPressContextMenuOnLinks"];
map["disableLongPressContextMenuOnLinks"];
settings.disableInputAccessoryView = map["disableInputAccessoryView"];
settings.underPageBackgroundColor = UtilColor.fromHex(map["underPageBackgroundColor"]);
settings.underPageBackgroundColor =
UtilColor.fromHex(map["underPageBackgroundColor"]);
settings.isTextInteractionEnabled = map["isTextInteractionEnabled"];
settings.isSiteSpecificQuirksModeEnabled = map["isSiteSpecificQuirksModeEnabled"];
settings.isSiteSpecificQuirksModeEnabled =
map["isSiteSpecificQuirksModeEnabled"];
settings.upgradeKnownHostsToHTTPS = map["upgradeKnownHostsToHTTPS"];
}
return settings;

View File

@ -525,8 +525,7 @@ abstract class WebView {
///
///**Supported Platforms/Implementations**:
///- Android native WebView ([Official API - WebChromeClient.onPermissionRequest](https://developer.android.com/reference/android/webkit/WebChromeClient#onPermissionRequest(android.webkit.PermissionRequest)))
final Future<PermissionResponse?> Function(
InAppWebViewController controller,
final Future<PermissionResponse?> Function(InAppWebViewController controller,
PermissionRequest permissionRequest)? onPermissionRequest;
///Use [onGeolocationPermissionsShowPrompt] instead.

View File

@ -4716,6 +4716,11 @@ class PermissionResponseAction {
///Grants origin the permission to access the given resources.
static const GRANT = const PermissionResponseAction._internal(1);
///Prompt the user for permission for the requested resource.
///
///**NOTE**: available only on iOS 15.0+. It will fallback to [DENY].
static const PROMPT = const PermissionResponseAction._internal(2);
bool operator ==(value) => value == _value;
@override
@ -4768,7 +4773,8 @@ class PermissionResourceType {
PermissionResourceType.RESOURCE_VIDEO_CAPTURE,
].toSet();
static final Set<PermissionResourceType> _appleValues = <PermissionResourceType>[
static final Set<PermissionResourceType> _appleValues =
<PermissionResourceType>[
PermissionResourceType.CAMERA,
PermissionResourceType.MICROPHONE,
PermissionResourceType.CAMERA_AND_MICROPHONE,
@ -4814,52 +4820,51 @@ class PermissionResourceType {
///Resource belongs to audio capture device, like microphone.
///
///**NOTE**: available only on Android.
static const RESOURCE_AUDIO_CAPTURE = const PermissionResourceType._internal('android.webkit.resource.AUDIO_CAPTURE');
static const RESOURCE_AUDIO_CAPTURE = const PermissionResourceType._internal(
'android.webkit.resource.AUDIO_CAPTURE');
///Resource will allow sysex messages to be sent to or received from MIDI devices.
///These messages are privileged operations, e.g. modifying sound libraries and sampling data, or even updating the MIDI device's firmware.
///Resource will allow sysex messages to be sent to or received from MIDI devices.
///These messages are privileged operations, e.g. modifying sound libraries and sampling data, or even updating the MIDI device's firmware.
///Permission may be requested for this resource in API levels 21 and above, if the Android device has been updated to WebView 45 or above.
///
///**NOTE**: available only on Android.
static const RESOURCE_MIDI_SYSEX =
const PermissionResourceType._internal('android.webkit.resource.MIDI_SYSEX');
static const RESOURCE_MIDI_SYSEX = const PermissionResourceType._internal(
'android.webkit.resource.MIDI_SYSEX');
///Resource belongs to protected media identifier. After the user grants this resource, the origin can use EME APIs to generate the license requests.
///
///**NOTE**: available only on Android.
static const RESOURCE_PROTECTED_MEDIA_ID =
const PermissionResourceType._internal('android.webkit.resource.PROTECTED_MEDIA_ID');
const PermissionResourceType._internal(
'android.webkit.resource.PROTECTED_MEDIA_ID');
///Resource belongs to video capture device, like camera.
///
///**NOTE**: available only on Android.
static const RESOURCE_VIDEO_CAPTURE =
const PermissionResourceType._internal('android.webkit.resource.VIDEO_CAPTURE');
static const RESOURCE_VIDEO_CAPTURE = const PermissionResourceType._internal(
'android.webkit.resource.VIDEO_CAPTURE');
///A media device that can capture video.
///
///**NOTE**: available only on iOS.
static const CAMERA =
const PermissionResourceType._internal(0);
static const CAMERA = const PermissionResourceType._internal(0);
///A media device that can capture audio.
///
///**NOTE**: available only on iOS.
static const MICROPHONE =
const PermissionResourceType._internal(1);
static const MICROPHONE = const PermissionResourceType._internal(1);
///A media device or devices that can capture audio and video.
///
///**NOTE**: available only on iOS.
static const CAMERA_AND_MICROPHONE =
const PermissionResourceType._internal(2);
const PermissionResourceType._internal(2);
///Resource belongs to the devices orientation and motion.
///
///**NOTE**: available only on iOS.
static const DEVICE_ORIENTATION_AND_MOTION =
const PermissionResourceType._internal('deviceOrientationAndMotion');
const PermissionResourceType._internal('deviceOrientationAndMotion');
bool operator ==(value) => value == _value;
@ -4873,15 +4878,16 @@ class PermissionRequest {
Uri origin;
///List of resources the web content wants to access.
///
///**NOTE for iOS**: this list will have only 1 element and will be used by the [PermissionResponse.action]
///as the resource to consider when applying the corresponding action.
List<PermissionResourceType> resources;
///The frame that initiates the request in the web view.
FrameInfo? frame;
PermissionRequest(
{required this.origin,
this.resources = const [],
this.frame});
{required this.origin, this.resources = const [], this.frame});
static PermissionRequest? fromMap(Map<String, dynamic>? map) {
if (map == null) {
@ -4890,8 +4896,7 @@ class PermissionRequest {
List<PermissionResourceType> resources = [];
if (map["resources"] != null) {
(map["resources"].cast<dynamic>() as List<dynamic>)
.forEach((element) {
(map["resources"].cast<dynamic>() as List<dynamic>).forEach((element) {
var resource = PermissionResourceType.fromValue(element);
if (resource != null) {
resources.add(resource);
@ -4907,7 +4912,7 @@ class PermissionRequest {
Map<String, dynamic> toMap() {
return {
"origin": origin.toString(),
"origin": origin.toString(),
"resources": resources.map((e) => e.toValue()).toList(),
"frame": frame?.toMap()
};
@ -4926,14 +4931,15 @@ class PermissionRequest {
///Class that represents the response used by the [WebView.onPermissionRequest] event.
class PermissionResponse {
///Resources granted to be accessed by origin.
///
///**NOTE for iOS**: not used. The [action] taken is based on the [PermissionRequest.resources].
List<PermissionResourceType> resources;
///Indicate the [PermissionResponseAction] to take in response of a permission request.
PermissionResponseAction? action;
PermissionResponse(
{this.resources = const [],
this.action = PermissionResponseAction.DENY});
{this.resources = const [], this.action = PermissionResponseAction.DENY});
Map<String, dynamic> toMap() {
return {
@ -4995,6 +5001,11 @@ class NavigationActionPolicy {
///Allow the navigation to continue.
static const ALLOW = const NavigationActionPolicy._internal(1);
///Turn the navigation into a download.
///
///**NOTE**: available only on iOS 14.5+. It will fallback to [CANCEL].
static const DOWNLOAD = const NavigationActionPolicy._internal(2);
bool operator ==(value) => value == _value;
@override
@ -5763,6 +5774,11 @@ class NavigationAction {
///**NOTE**: available only on iOS.
FrameInfo? targetFrame;
///A value indicating whether the web content used a download attribute to indicate that this should be downloaded.
///
///**NOTE**: available only on iOS.
bool? shouldPerformDownload;
NavigationAction(
{required this.request,
required this.isForMainFrame,
@ -5775,7 +5791,8 @@ class NavigationAction {
@Deprecated("Use sourceFrame instead") this.iosSourceFrame,
this.sourceFrame,
@Deprecated("Use targetFrame instead") this.iosTargetFrame,
this.targetFrame}) {
this.targetFrame,
this.shouldPerformDownload}) {
// ignore: deprecated_member_use_from_same_package
this.hasGesture = this.hasGesture ?? this.androidHasGesture;
// ignore: deprecated_member_use_from_same_package
@ -5820,7 +5837,8 @@ class NavigationAction {
// ignore: deprecated_member_use_from_same_package
IOSWKFrameInfo.fromMap(map["targetFrame"]?.cast<String, dynamic>()),
targetFrame:
FrameInfo.fromMap(map["targetFrame"]?.cast<String, dynamic>()));
FrameInfo.fromMap(map["targetFrame"]?.cast<String, dynamic>()),
shouldPerformDownload: map["shouldPerformDownload"]);
}
Map<String, dynamic> toMap() {
@ -5849,6 +5867,7 @@ class NavigationAction {
"iosTargetFrame": targetFrame?.toMap() ?? iosTargetFrame?.toMap(),
// ignore: deprecated_member_use_from_same_package
"targetFrame": targetFrame?.toMap() ?? iosTargetFrame?.toMap(),
"shouldPerformDownload": shouldPerformDownload
};
}
@ -8955,6 +8974,11 @@ class NavigationResponseAction {
///Allow the navigation to continue.
static const ALLOW = const NavigationResponseAction._internal(1);
///Turn the navigation into a download.
///
///**NOTE**: available only on iOS 14.5+. It will fallback to [CANCEL].
static const DOWNLOAD = const NavigationResponseAction._internal(2);
bool operator ==(value) => value == _value;
@override
@ -10687,19 +10711,16 @@ class MediaPlaybackState {
static const NONE = const MediaPlaybackState._internal(0);
///The media is playing.
static const PLAYING =
const MediaPlaybackState._internal(1);
static const PLAYING = const MediaPlaybackState._internal(1);
///The media playback is paused.
static const PAUSED =
const MediaPlaybackState._internal(2);
static const PAUSED = const MediaPlaybackState._internal(2);
///The media is not playing, and cannot be resumed until the user revokes the suspension.
static const SUSPENDED =
const MediaPlaybackState._internal(3);
static const SUSPENDED = const MediaPlaybackState._internal(3);
bool operator ==(value) => value == _value;
@override
int get hashCode => _value.hashCode;
}
}