Isolate extension WebView profiles and follow host proxy settings

This commit is contained in:
Levi committed 2026-09-14 00:30:52 +08:00
1 parent cee5f3336e
commit a0e84a75b1
556 files changed
+71097 -31

No files matched your search

@@ -0,0 +1,218 @@
import 'dart:async';
import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
/// Object specifying creation parameters for creating a [IOSChromeSafariBrowser].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformChromeSafariBrowserCreationParams] for
/// more information.
@immutable
class IOSChromeSafariBrowserCreationParams
extends PlatformChromeSafariBrowserCreationParams {
/// Creates a new [IOSChromeSafariBrowserCreationParams] instance.
const IOSChromeSafariBrowserCreationParams();
/// Creates a [IOSChromeSafariBrowserCreationParams] instance based on [PlatformChromeSafariBrowserCreationParams].
factory IOSChromeSafariBrowserCreationParams.fromPlatformChromeSafariBrowserCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformChromeSafariBrowserCreationParams params) {
return IOSChromeSafariBrowserCreationParams();
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformChromeSafariBrowser}
class IOSChromeSafariBrowser extends PlatformChromeSafariBrowser
with ChannelController {
@override
final String id = IdGenerator.generate();
/// Constructs a [IOSChromeSafariBrowser].
IOSChromeSafariBrowser(PlatformChromeSafariBrowserCreationParams params)
: super.implementation(
params is IOSChromeSafariBrowserCreationParams
? params
: IOSChromeSafariBrowserCreationParams
.fromPlatformChromeSafariBrowserCreationParams(params),
);
static final IOSChromeSafariBrowser _staticValue =
IOSChromeSafariBrowser(IOSChromeSafariBrowserCreationParams());
/// Provide static access.
factory IOSChromeSafariBrowser.static() {
return _staticValue;
}
Map<int, ChromeSafariBrowserMenuItem> _menuItems = new HashMap();
bool _isOpened = false;
static const MethodChannel _staticChannel =
const MethodChannel('com.pichillilorenzo/flutter_chromesafaribrowser');
_init() {
channel =
MethodChannel('com.pichillilorenzo/flutter_chromesafaribrowser_$id');
handler = _handleMethod;
initMethodCallHandler();
}
_debugLog(String method, dynamic args) {
debugLog(
className: this.runtimeType.toString(),
id: id,
debugLoggingSettings: PlatformChromeSafariBrowser.debugLoggingSettings,
method: method,
args: args);
}
Future<dynamic> _handleMethod(MethodCall call) async {
_debugLog(call.method, call.arguments);
switch (call.method) {
case "onOpened":
eventHandler?.onOpened();
break;
case "onCompletedInitialLoad":
final bool? didLoadSuccessfully = call.arguments["didLoadSuccessfully"];
eventHandler?.onCompletedInitialLoad(didLoadSuccessfully);
break;
case "onInitialLoadDidRedirect":
final String? url = call.arguments["url"];
final WebUri? uri = url != null ? WebUri(url) : null;
eventHandler?.onInitialLoadDidRedirect(uri);
break;
case "onWillOpenInBrowser":
eventHandler?.onWillOpenInBrowser();
break;
case "onClosed":
_isOpened = false;
final onClosed = eventHandler?.onClosed;
dispose();
onClosed?.call();
break;
case "onItemActionPerform":
String url = call.arguments["url"];
String title = call.arguments["title"];
int id = call.arguments["id"].toInt();
if (this._menuItems[id] != null) {
if (this._menuItems[id]?.action != null) {
this._menuItems[id]?.action!(url, title);
}
if (this._menuItems[id]?.onClick != null) {
this._menuItems[id]?.onClick!(WebUri(url), title);
}
}
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
}
@override
Future<void> open(
{WebUri? url,
Map<String, String>? headers,
List<WebUri>? otherLikelyURLs,
WebUri? referrer,
@Deprecated('Use settings instead')
// ignore: deprecated_member_use_from_same_package
ChromeSafariBrowserClassOptions? options,
ChromeSafariBrowserSettings? settings}) async {
assert(!_isOpened, 'The browser is already opened.');
_isOpened = true;
assert(url != null, 'The specified URL must not be null on iOS.');
assert(['http', 'https'].contains(url!.scheme),
'The specified URL has an unsupported scheme. Only HTTP and HTTPS URLs are supported on iOS.');
if (url != null) {
assert(url.toString().isNotEmpty, 'The specified URL must not be empty.');
}
_init();
List<Map<String, dynamic>> menuItemList = [];
_menuItems.forEach((key, value) {
menuItemList.add(value.toMap());
});
var initialSettings = settings?.toMap() ??
options?.toMap() ??
ChromeSafariBrowserSettings().toMap();
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('id', () => id);
args.putIfAbsent('url', () => url?.toString());
args.putIfAbsent('headers', () => headers);
args.putIfAbsent('otherLikelyURLs',
() => otherLikelyURLs?.map((e) => e.toString()).toList());
args.putIfAbsent('referrer', () => referrer?.toString());
args.putIfAbsent('settings', () => initialSettings);
args.putIfAbsent('menuItemList', () => menuItemList);
await _staticChannel.invokeMethod('open', args);
}
@override
Future<void> close() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod("close", args);
}
@override
void addMenuItem(ChromeSafariBrowserMenuItem menuItem) {
this._menuItems[menuItem.id] = menuItem;
}
@override
void addMenuItems(List<ChromeSafariBrowserMenuItem> menuItems) {
menuItems.forEach((menuItem) {
this._menuItems[menuItem.id] = menuItem;
});
}
@override
Future<bool> isAvailable() async {
Map<String, dynamic> args = <String, dynamic>{};
return await _staticChannel.invokeMethod<bool>("isAvailable", args) ??
false;
}
@override
Future<void> clearWebsiteData() async {
Map<String, dynamic> args = <String, dynamic>{};
await _staticChannel.invokeMethod("clearWebsiteData", args);
}
@override
Future<PrewarmingToken?> prewarmConnections(List<WebUri> URLs) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('URLs', () => URLs.map((e) => e.toString()).toList());
Map<String, dynamic>? result =
(await _staticChannel.invokeMethod("prewarmConnections", args))
?.cast<String, dynamic>();
return PrewarmingToken.fromMap(result);
}
@override
Future<void> invalidatePrewarmingToken(
PrewarmingToken prewarmingToken) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('prewarmingToken', () => prewarmingToken.toMap());
await _staticChannel.invokeMethod("invalidatePrewarmingToken", args);
}
@override
bool isOpened() {
return _isOpened;
}
@override
@mustCallSuper
void dispose() {
super.dispose();
disposeChannel();
}
}
@@ -0,0 +1 @@
export 'chrome_safari_browser.dart';
@@ -0,0 +1,433 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'in_app_webview/headless_in_app_webview.dart';
import 'platform_util.dart';
/// Object specifying creation parameters for creating a [IOSCookieManager].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformCookieManagerCreationParams] for
/// more information.
@immutable
class IOSCookieManagerCreationParams
extends PlatformCookieManagerCreationParams {
/// Creates a new [IOSCookieManagerCreationParams] instance.
const IOSCookieManagerCreationParams(
// This parameter prevents breaking changes later.
// ignore: avoid_unused_constructor_parameters
PlatformCookieManagerCreationParams params,
) : super();
/// Creates a [IOSCookieManagerCreationParams] instance based on [PlatformCookieManagerCreationParams].
factory IOSCookieManagerCreationParams.fromPlatformCookieManagerCreationParams(
PlatformCookieManagerCreationParams params) {
return IOSCookieManagerCreationParams(params);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformCookieManager}
class IOSCookieManager extends PlatformCookieManager with ChannelController {
/// Creates a new [IOSCookieManager].
IOSCookieManager(PlatformCookieManagerCreationParams params)
: super.implementation(
params is IOSCookieManagerCreationParams
? params
: IOSCookieManagerCreationParams
.fromPlatformCookieManagerCreationParams(params),
) {
channel = const MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_cookiemanager');
handler = handleMethod;
initMethodCallHandler();
}
static IOSCookieManager? _instance;
///Gets the [IOSCookieManager] shared instance.
static IOSCookieManager instance() {
return (_instance != null) ? _instance! : _init();
}
static IOSCookieManager _init() {
_instance = IOSCookieManager(IOSCookieManagerCreationParams(
const PlatformCookieManagerCreationParams()));
return _instance!;
}
Future<dynamic> _handleMethod(MethodCall call) async {}
@override
Future<bool> setCookie(
{required WebUri url,
required String name,
required String value,
String path = "/",
String? domain,
int? expiresDate,
int? maxAge,
bool? isSecure,
bool? isHttpOnly,
HTTPCookieSameSitePolicy? sameSite,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
webViewController = webViewController ?? iosBelow11WebViewController;
assert(url.toString().isNotEmpty);
assert(name.isNotEmpty);
assert(value.isNotEmpty);
assert(path.isNotEmpty);
if (await _shouldUseJavascript()) {
await _setCookieWithJavaScript(
url: url,
name: name,
value: value,
domain: domain,
path: path,
expiresDate: expiresDate,
maxAge: maxAge,
isSecure: isSecure,
sameSite: sameSite,
webViewController: webViewController);
return true;
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('url', () => url.toString());
args.putIfAbsent('name', () => name);
args.putIfAbsent('value', () => value);
args.putIfAbsent('domain', () => domain);
args.putIfAbsent('path', () => path);
args.putIfAbsent('expiresDate', () => expiresDate?.toString());
args.putIfAbsent('maxAge', () => maxAge);
args.putIfAbsent('isSecure', () => isSecure);
args.putIfAbsent('isHttpOnly', () => isHttpOnly);
args.putIfAbsent('sameSite', () => sameSite?.toNativeValue());
return await channel?.invokeMethod<bool>('setCookie', args) ?? false;
}
Future<void> _setCookieWithJavaScript(
{required WebUri url,
required String name,
required String value,
String path = "/",
String? domain,
int? expiresDate,
int? maxAge,
bool? isSecure,
HTTPCookieSameSitePolicy? sameSite,
PlatformInAppWebViewController? webViewController}) async {
var cookieValue = name + "=" + value + "; Path=" + path;
if (domain != null) cookieValue += "; Domain=" + domain;
if (expiresDate != null)
cookieValue += "; Expires=" + await _getCookieExpirationDate(expiresDate);
if (maxAge != null) cookieValue += "; Max-Age=" + maxAge.toString();
if (isSecure != null && isSecure) cookieValue += "; Secure";
if (sameSite != null)
cookieValue += "; SameSite=" + sameSite.toNativeValue();
cookieValue += ";";
if (webViewController != null) {
final javaScriptEnabled =
(await webViewController.getSettings())?.javaScriptEnabled ?? false;
if (javaScriptEnabled) {
await webViewController.evaluateJavascript(
source: 'document.cookie="$cookieValue"');
return;
}
}
final setCookieCompleter = Completer<void>();
final headlessWebView =
IOSHeadlessInAppWebView(IOSHeadlessInAppWebViewCreationParams(
initialUrlRequest: URLRequest(url: url),
onLoadStop: (controller, url) async {
await controller.evaluateJavascript(
source: 'document.cookie="$cookieValue"');
setCookieCompleter.complete();
}));
await headlessWebView.run();
await setCookieCompleter.future;
await headlessWebView.dispose();
}
@override
Future<List<Cookie>> getCookies(
{required WebUri url,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
webViewController = webViewController ?? iosBelow11WebViewController;
if (await _shouldUseJavascript()) {
return await _getCookiesWithJavaScript(
url: url, webViewController: webViewController);
}
List<Cookie> cookies = [];
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('url', () => url.toString());
List<dynamic> cookieListMap =
await channel?.invokeMethod<List>('getCookies', args) ?? [];
cookieListMap = cookieListMap.cast<Map<dynamic, dynamic>>();
cookieListMap.forEach((cookieMap) {
cookies.add(Cookie(
name: cookieMap["name"],
value: cookieMap["value"],
expiresDate: cookieMap["expiresDate"],
isSessionOnly: cookieMap["isSessionOnly"],
domain: cookieMap["domain"],
sameSite:
HTTPCookieSameSitePolicy.fromNativeValue(cookieMap["sameSite"]),
isSecure: cookieMap["isSecure"],
isHttpOnly: cookieMap["isHttpOnly"],
path: cookieMap["path"]));
});
return cookies;
}
Future<List<Cookie>> _getCookiesWithJavaScript(
{required WebUri url,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
List<Cookie> cookies = [];
if (webViewController != null) {
final javaScriptEnabled =
(await webViewController.getSettings())?.javaScriptEnabled ?? false;
if (javaScriptEnabled) {
List<String> documentCookies = (await webViewController
.evaluateJavascript(source: 'document.cookie') as String)
.split(';')
.map((documentCookie) => documentCookie.trim())
.toList();
documentCookies.forEach((documentCookie) {
List<String> cookie = documentCookie.split('=');
if (cookie.length > 1) {
cookies.add(Cookie(
name: cookie[0],
value: cookie[1],
));
}
});
return cookies;
}
}
final pageLoaded = Completer<void>();
final headlessWebView =
IOSHeadlessInAppWebView(IOSHeadlessInAppWebViewCreationParams(
initialUrlRequest: URLRequest(url: url),
onLoadStop: (controller, url) async {
pageLoaded.complete();
},
));
await headlessWebView.run();
await pageLoaded.future;
List<String> documentCookies = (await headlessWebView.webViewController!
.evaluateJavascript(source: 'document.cookie') as String)
.split(';')
.map((documentCookie) => documentCookie.trim())
.toList();
documentCookies.forEach((documentCookie) {
List<String> cookie = documentCookie.split('=');
if (cookie.length > 1) {
cookies.add(Cookie(
name: cookie[0],
value: cookie[1],
));
}
});
await headlessWebView.dispose();
return cookies;
}
@override
Future<Cookie?> getCookie(
{required WebUri url,
required String name,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
assert(name.isNotEmpty);
webViewController = webViewController ?? iosBelow11WebViewController;
if (await _shouldUseJavascript()) {
List<Cookie> cookies = await _getCookiesWithJavaScript(
url: url, webViewController: webViewController);
return cookies
.cast<Cookie?>()
.firstWhere((cookie) => cookie!.name == name, orElse: () => null);
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('url', () => url.toString());
List<dynamic> cookies =
await channel?.invokeMethod<List>('getCookies', args) ?? [];
cookies = cookies.cast<Map<dynamic, dynamic>>();
for (var i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].cast<String, dynamic>();
if (cookies[i]["name"] == name)
return Cookie(
name: cookies[i]["name"],
value: cookies[i]["value"],
expiresDate: cookies[i]["expiresDate"],
isSessionOnly: cookies[i]["isSessionOnly"],
domain: cookies[i]["domain"],
sameSite: HTTPCookieSameSitePolicy.fromNativeValue(
cookies[i]["sameSite"]),
isSecure: cookies[i]["isSecure"],
isHttpOnly: cookies[i]["isHttpOnly"],
path: cookies[i]["path"]);
}
return null;
}
@override
Future<bool> deleteCookie(
{required WebUri url,
required String name,
String path = "/",
String? domain,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
assert(name.isNotEmpty);
webViewController = webViewController ?? iosBelow11WebViewController;
if (await _shouldUseJavascript()) {
await _setCookieWithJavaScript(
url: url,
name: name,
value: "",
path: path,
domain: domain,
maxAge: -1,
webViewController: webViewController);
return true;
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('url', () => url.toString());
args.putIfAbsent('name', () => name);
args.putIfAbsent('domain', () => domain);
args.putIfAbsent('path', () => path);
return await channel?.invokeMethod<bool>('deleteCookie', args) ?? false;
}
@override
Future<bool> deleteCookies(
{required WebUri url,
String path = "/",
String? domain,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
webViewController = webViewController ?? iosBelow11WebViewController;
if (await _shouldUseJavascript()) {
List<Cookie> cookies = await _getCookiesWithJavaScript(
url: url, webViewController: webViewController);
for (var i = 0; i < cookies.length; i++) {
await _setCookieWithJavaScript(
url: url,
name: cookies[i].name,
value: "",
path: path,
domain: domain,
maxAge: -1,
webViewController: webViewController);
}
return true;
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('url', () => url.toString());
args.putIfAbsent('domain', () => domain);
args.putIfAbsent('path', () => path);
return await channel?.invokeMethod<bool>('deleteCookies', args) ?? false;
}
@override
Future<bool> deleteAllCookies() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('deleteAllCookies', args) ?? false;
}
@override
Future<List<Cookie>> getAllCookies() async {
List<Cookie> cookies = [];
Map<String, dynamic> args = <String, dynamic>{};
List<dynamic> cookieListMap =
await channel?.invokeMethod<List>('getAllCookies', args) ?? [];
cookieListMap = cookieListMap.cast<Map<dynamic, dynamic>>();
cookieListMap.forEach((cookieMap) {
cookies.add(Cookie(
name: cookieMap["name"],
value: cookieMap["value"],
expiresDate: cookieMap["expiresDate"],
isSessionOnly: cookieMap["isSessionOnly"],
domain: cookieMap["domain"],
sameSite:
HTTPCookieSameSitePolicy.fromNativeValue(cookieMap["sameSite"]),
isSecure: cookieMap["isSecure"],
isHttpOnly: cookieMap["isHttpOnly"],
path: cookieMap["path"]));
});
return cookies;
}
Future<String> _getCookieExpirationDate(int expiresDate) async {
var platformUtil = PlatformUtil.instance();
var dateTime = DateTime.fromMillisecondsSinceEpoch(expiresDate).toUtc();
return !kIsWeb
? await platformUtil.formatDate(
date: dateTime,
format: 'EEE, dd MMM yyyy hh:mm:ss z',
locale: 'en_US',
timezone: 'GMT')
: await platformUtil.getWebCookieExpirationDate(date: dateTime);
}
Future<bool> _shouldUseJavascript() async {
final platformUtil = PlatformUtil.instance();
final systemVersion = await platformUtil.getSystemVersion();
return systemVersion.compareTo("10.13") == -1;
}
@override
void dispose() {
// empty
}
}
extension InternalCookieManager on IOSCookieManager {
get handleMethod => _handleMethod;
}
@@ -0,0 +1,148 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
/// Object specifying creation parameters for creating a [IOSFindInteractionController].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformFindInteractionControllerCreationParams] for
/// more information.
@immutable
class IOSFindInteractionControllerCreationParams
extends PlatformFindInteractionControllerCreationParams {
/// Creates a new [IOSFindInteractionControllerCreationParams] instance.
const IOSFindInteractionControllerCreationParams(
{super.onFindResultReceived});
/// Creates a [IOSFindInteractionControllerCreationParams] instance based on [PlatformFindInteractionControllerCreationParams].
factory IOSFindInteractionControllerCreationParams.fromPlatformFindInteractionControllerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformFindInteractionControllerCreationParams params) {
return IOSFindInteractionControllerCreationParams(
onFindResultReceived: params.onFindResultReceived);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController}
class IOSFindInteractionController extends PlatformFindInteractionController
with ChannelController {
/// Constructs a [IOSFindInteractionController].
IOSFindInteractionController(
PlatformFindInteractionControllerCreationParams params)
: super.implementation(
params is IOSFindInteractionControllerCreationParams
? params
: IOSFindInteractionControllerCreationParams
.fromPlatformFindInteractionControllerCreationParams(params),
);
_debugLog(String method, dynamic args) {
debugLog(
className: this.runtimeType.toString(),
debugLoggingSettings:
PlatformFindInteractionController.debugLoggingSettings,
method: method,
args: args);
}
Future<dynamic> _handleMethod(MethodCall call) async {
_debugLog(call.method, call.arguments);
switch (call.method) {
case "onFindResultReceived":
if (onFindResultReceived != null) {
int activeMatchOrdinal = call.arguments["activeMatchOrdinal"];
int numberOfMatches = call.arguments["numberOfMatches"];
bool isDoneCounting = call.arguments["isDoneCounting"];
onFindResultReceived!(
this, activeMatchOrdinal, numberOfMatches, isDoneCounting);
}
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
return null;
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.findAll}
Future<void> findAll({String? find}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('find', () => find);
await channel?.invokeMethod('findAll', args);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.findNext}
Future<void> findNext({bool forward = true}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('forward', () => forward);
await channel?.invokeMethod('findNext', args);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.clearMatches}
Future<void> clearMatches() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('clearMatches', args);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.setSearchText}
Future<void> setSearchText(String? searchText) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('searchText', () => searchText);
await channel?.invokeMethod('setSearchText', args);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.getSearchText}
Future<String?> getSearchText() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<String?>('getSearchText', args);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.isFindNavigatorVisible}
Future<bool?> isFindNavigatorVisible() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool?>('isFindNavigatorVisible', args);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.updateResultCount}
Future<void> updateResultCount() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('updateResultCount', args);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.presentFindNavigator}
Future<void> presentFindNavigator() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('presentFindNavigator', args);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.dismissFindNavigator}
Future<void> dismissFindNavigator() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('dismissFindNavigator', args);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.getActiveFindSession}
Future<FindSession?> getActiveFindSession() async {
Map<String, dynamic> args = <String, dynamic>{};
Map<String, dynamic>? result =
(await channel?.invokeMethod('getActiveFindSession', args))
?.cast<String, dynamic>();
return FindSession.fromMap(result);
}
///{@macro flutter_inappwebview_platform_interface.PlatformFindInteractionController.dispose}
@override
void dispose({bool isKeepAlive = false}) {
disposeChannel(removeMethodCallHandler: !isKeepAlive);
}
}
extension InternalFindInteractionController on IOSFindInteractionController {
void init(dynamic id) {
channel = MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_find_interaction_$id');
handler = _handleMethod;
initMethodCallHandler();
}
}
@@ -0,0 +1,2 @@
export 'find_interaction_controller.dart'
hide InternalFindInteractionController;
@@ -0,0 +1,154 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
/// Object specifying creation parameters for creating a [IOSHttpAuthCredentialDatabase].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformHttpAuthCredentialDatabaseCreationParams] for
/// more information.
@immutable
class IOSHttpAuthCredentialDatabaseCreationParams
extends PlatformHttpAuthCredentialDatabaseCreationParams {
/// Creates a new [IOSHttpAuthCredentialDatabaseCreationParams] instance.
const IOSHttpAuthCredentialDatabaseCreationParams(
// This parameter prevents breaking changes later.
// ignore: avoid_unused_constructor_parameters
PlatformHttpAuthCredentialDatabaseCreationParams params,
) : super();
/// Creates a [IOSHttpAuthCredentialDatabaseCreationParams] instance based on [PlatformHttpAuthCredentialDatabaseCreationParams].
factory IOSHttpAuthCredentialDatabaseCreationParams.fromPlatformHttpAuthCredentialDatabaseCreationParams(
PlatformHttpAuthCredentialDatabaseCreationParams params) {
return IOSHttpAuthCredentialDatabaseCreationParams(params);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformHttpAuthCredentialDatabase}
class IOSHttpAuthCredentialDatabase extends PlatformHttpAuthCredentialDatabase
with ChannelController {
/// Creates a new [IOSHttpAuthCredentialDatabase].
IOSHttpAuthCredentialDatabase(
PlatformHttpAuthCredentialDatabaseCreationParams params)
: super.implementation(
params is IOSHttpAuthCredentialDatabaseCreationParams
? params
: IOSHttpAuthCredentialDatabaseCreationParams
.fromPlatformHttpAuthCredentialDatabaseCreationParams(params),
) {
channel = const MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_credential_database');
handler = handleMethod;
initMethodCallHandler();
}
static IOSHttpAuthCredentialDatabase? _instance;
///Gets the database shared instance.
static IOSHttpAuthCredentialDatabase instance() {
return (_instance != null) ? _instance! : _init();
}
static IOSHttpAuthCredentialDatabase _init() {
_instance = IOSHttpAuthCredentialDatabase(
IOSHttpAuthCredentialDatabaseCreationParams(
const PlatformHttpAuthCredentialDatabaseCreationParams()));
return _instance!;
}
Future<dynamic> _handleMethod(MethodCall call) async {}
@override
Future<List<URLProtectionSpaceHttpAuthCredentials>>
getAllAuthCredentials() async {
Map<String, dynamic> args = <String, dynamic>{};
List<dynamic> allCredentials =
await channel?.invokeMethod<List>('getAllAuthCredentials', args) ?? [];
List<URLProtectionSpaceHttpAuthCredentials> result = [];
for (Map<dynamic, dynamic> map in allCredentials) {
var element = URLProtectionSpaceHttpAuthCredentials.fromMap(
map.cast<String, dynamic>());
if (element != null) {
result.add(element);
}
}
return result;
}
@override
Future<List<URLCredential>> getHttpAuthCredentials(
{required URLProtectionSpace protectionSpace}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("host", () => protectionSpace.host);
args.putIfAbsent("protocol", () => protectionSpace.protocol);
args.putIfAbsent("realm", () => protectionSpace.realm);
args.putIfAbsent("port", () => protectionSpace.port);
List<dynamic> credentialList =
await channel?.invokeMethod<List>('getHttpAuthCredentials', args) ?? [];
List<URLCredential> credentials = [];
for (Map<dynamic, dynamic> map in credentialList) {
var credential = URLCredential.fromMap(map.cast<String, dynamic>());
if (credential != null) {
credentials.add(credential);
}
}
return credentials;
}
@override
Future<void> setHttpAuthCredential(
{required URLProtectionSpace protectionSpace,
required URLCredential credential}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("host", () => protectionSpace.host);
args.putIfAbsent("protocol", () => protectionSpace.protocol);
args.putIfAbsent("realm", () => protectionSpace.realm);
args.putIfAbsent("port", () => protectionSpace.port);
args.putIfAbsent("username", () => credential.username);
args.putIfAbsent("password", () => credential.password);
await channel?.invokeMethod('setHttpAuthCredential', args);
}
@override
Future<void> removeHttpAuthCredential(
{required URLProtectionSpace protectionSpace,
required URLCredential credential}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("host", () => protectionSpace.host);
args.putIfAbsent("protocol", () => protectionSpace.protocol);
args.putIfAbsent("realm", () => protectionSpace.realm);
args.putIfAbsent("port", () => protectionSpace.port);
args.putIfAbsent("username", () => credential.username);
args.putIfAbsent("password", () => credential.password);
await channel?.invokeMethod('removeHttpAuthCredential', args);
}
@override
Future<void> removeHttpAuthCredentials(
{required URLProtectionSpace protectionSpace}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("host", () => protectionSpace.host);
args.putIfAbsent("protocol", () => protectionSpace.protocol);
args.putIfAbsent("realm", () => protectionSpace.realm);
args.putIfAbsent("port", () => protectionSpace.port);
await channel?.invokeMethod('removeHttpAuthCredentials', args);
}
@override
Future<void> clearAllAuthCredentials() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('clearAllAuthCredentials', args);
}
@override
void dispose() {
// empty
}
}
extension InternalHttpAuthCredentialDatabase on IOSHttpAuthCredentialDatabase {
get handleMethod => _handleMethod;
}
@@ -0,0 +1,374 @@
import 'dart:async';
import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import '../find_interaction/find_interaction_controller.dart';
import '../in_app_webview/in_app_webview_controller.dart';
import '../pull_to_refresh/pull_to_refresh_controller.dart';
/// Object specifying creation parameters for creating a [IOSInAppBrowser].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformInAppBrowserCreationParams] for
/// more information.
class IOSInAppBrowserCreationParams extends PlatformInAppBrowserCreationParams {
/// Creates a new [IOSInAppBrowserCreationParams] instance.
IOSInAppBrowserCreationParams(
{super.contextMenu,
this.pullToRefreshController,
this.findInteractionController,
super.initialUserScripts,
super.windowId});
/// Creates a [IOSInAppBrowserCreationParams] instance based on [PlatformInAppBrowserCreationParams].
factory IOSInAppBrowserCreationParams.fromPlatformInAppBrowserCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformInAppBrowserCreationParams params) {
return IOSInAppBrowserCreationParams(
contextMenu: params.contextMenu,
pullToRefreshController:
params.pullToRefreshController as IOSPullToRefreshController?,
findInteractionController:
params.findInteractionController as IOSFindInteractionController?,
initialUserScripts: params.initialUserScripts,
windowId: params.windowId);
}
@override
final IOSFindInteractionController? findInteractionController;
@override
final IOSPullToRefreshController? pullToRefreshController;
}
///{@macro flutter_inappwebview_platform_interface.PlatformInAppBrowser}
class IOSInAppBrowser extends PlatformInAppBrowser with ChannelController {
@override
final String id = IdGenerator.generate();
/// Constructs a [IOSInAppBrowser].
IOSInAppBrowser(PlatformInAppBrowserCreationParams params)
: super.implementation(
params is IOSInAppBrowserCreationParams
? params
: IOSInAppBrowserCreationParams
.fromPlatformInAppBrowserCreationParams(params),
) {
_contextMenu = params.contextMenu;
}
static final IOSInAppBrowser _staticValue =
IOSInAppBrowser(IOSInAppBrowserCreationParams());
/// Provide static access.
factory IOSInAppBrowser.static() {
return _staticValue;
}
IOSInAppBrowserCreationParams get _iosParams =>
params as IOSInAppBrowserCreationParams;
static const MethodChannel _staticChannel =
const MethodChannel('com.pichillilorenzo/flutter_inappbrowser');
ContextMenu? _contextMenu;
@override
ContextMenu? get contextMenu => _contextMenu;
Map<int, InAppBrowserMenuItem> _menuItems = HashMap();
bool _isOpened = false;
IOSInAppWebViewController? _webViewController;
@override
IOSInAppWebViewController? get webViewController {
return _isOpened ? _webViewController : null;
}
_init() {
channel = MethodChannel('com.pichillilorenzo/flutter_inappbrowser_$id');
handler = _handleMethod;
initMethodCallHandler();
_webViewController = IOSInAppWebViewController.fromInAppBrowser(
IOSInAppWebViewControllerCreationParams(id: id),
channel!,
this,
this.initialUserScripts);
_iosParams.pullToRefreshController?.init(id);
_iosParams.findInteractionController?.init(id);
}
_debugLog(String method, dynamic args) {
debugLog(
className: this.runtimeType.toString(),
id: id,
debugLoggingSettings: PlatformInAppBrowser.debugLoggingSettings,
method: method,
args: args);
}
Future<dynamic> _handleMethod(MethodCall call) async {
switch (call.method) {
case "onBrowserCreated":
_debugLog(call.method, call.arguments);
eventHandler?.onBrowserCreated();
break;
case "onMenuItemClicked":
_debugLog(call.method, call.arguments);
int id = call.arguments["id"].toInt();
if (this._menuItems[id] != null) {
if (this._menuItems[id]?.onClick != null) {
this._menuItems[id]?.onClick!();
}
}
break;
case "onExit":
_debugLog(call.method, call.arguments);
_isOpened = false;
final onExit = eventHandler?.onExit;
dispose();
onExit?.call();
break;
default:
return _webViewController?.handleMethod(call);
}
}
Map<String, dynamic> _prepareOpenRequest(
{@Deprecated('Use settings instead') InAppBrowserClassOptions? options,
InAppBrowserClassSettings? settings}) {
assert(!_isOpened, 'The browser is already opened.');
_isOpened = true;
_init();
var initialSettings = settings?.toMap() ??
options?.toMap() ??
InAppBrowserClassSettings().toMap();
Map<String, dynamic> pullToRefreshSettings =
pullToRefreshController?.settings.toMap() ??
pullToRefreshController?.options.toMap() ??
PullToRefreshSettings(enabled: false).toMap();
List<Map<String, dynamic>> menuItemList = [];
_menuItems.forEach((key, value) {
menuItemList.add(value.toMap());
});
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('id', () => id);
args.putIfAbsent('settings', () => initialSettings);
args.putIfAbsent('contextMenu', () => contextMenu?.toMap() ?? {});
args.putIfAbsent('windowId', () => windowId);
args.putIfAbsent('initialUserScripts',
() => initialUserScripts?.map((e) => e.toMap()).toList() ?? []);
args.putIfAbsent('pullToRefreshSettings', () => pullToRefreshSettings);
args.putIfAbsent('menuItems', () => menuItemList);
return args;
}
@override
Future<void> openUrlRequest(
{required URLRequest urlRequest,
// ignore: deprecated_member_use_from_same_package
@Deprecated('Use settings instead') InAppBrowserClassOptions? options,
InAppBrowserClassSettings? settings}) async {
assert(urlRequest.url != null && urlRequest.url.toString().isNotEmpty);
Map<String, dynamic> args =
_prepareOpenRequest(options: options, settings: settings);
args.putIfAbsent('urlRequest', () => urlRequest.toMap());
await _staticChannel.invokeMethod('open', args);
}
@override
Future<void> openFile(
{required String assetFilePath,
// ignore: deprecated_member_use_from_same_package
@Deprecated('Use settings instead') InAppBrowserClassOptions? options,
InAppBrowserClassSettings? settings}) async {
assert(assetFilePath.isNotEmpty);
Map<String, dynamic> args =
_prepareOpenRequest(options: options, settings: settings);
args.putIfAbsent('assetFilePath', () => assetFilePath);
await _staticChannel.invokeMethod('open', args);
}
@override
Future<void> openData(
{required String data,
String mimeType = "text/html",
String encoding = "utf8",
WebUri? baseUrl,
@Deprecated("Use historyUrl instead") Uri? androidHistoryUrl,
WebUri? historyUrl,
// ignore: deprecated_member_use_from_same_package
@Deprecated('Use settings instead') InAppBrowserClassOptions? options,
InAppBrowserClassSettings? settings}) async {
Map<String, dynamic> args =
_prepareOpenRequest(options: options, settings: settings);
args.putIfAbsent('data', () => data);
args.putIfAbsent('mimeType', () => mimeType);
args.putIfAbsent('encoding', () => encoding);
args.putIfAbsent('baseUrl', () => baseUrl?.toString() ?? "about:blank");
args.putIfAbsent('historyUrl',
() => (historyUrl ?? androidHistoryUrl)?.toString() ?? "about:blank");
await _staticChannel.invokeMethod('open', args);
}
@override
Future<void> openWithSystemBrowser({required WebUri url}) async {
assert(url.toString().isNotEmpty);
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('url', () => url.toString());
return await _staticChannel.invokeMethod('openWithSystemBrowser', args);
}
@override
void addMenuItem(InAppBrowserMenuItem menuItem) {
_menuItems[menuItem.id] = menuItem;
}
@override
void addMenuItems(List<InAppBrowserMenuItem> menuItems) {
menuItems.forEach((menuItem) {
_menuItems[menuItem.id] = menuItem;
});
}
@override
bool removeMenuItem(InAppBrowserMenuItem menuItem) {
return _menuItems.remove(menuItem.id) != null;
}
@override
void removeMenuItems(List<InAppBrowserMenuItem> menuItems) {
for (final menuItem in menuItems) {
removeMenuItem(menuItem);
}
}
@override
void removeAllMenuItem() {
_menuItems.clear();
}
@override
bool hasMenuItem(InAppBrowserMenuItem menuItem) {
return _menuItems.containsKey(menuItem.id);
}
@override
Future<void> show() async {
assert(_isOpened, 'The browser is not opened.');
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('show', args);
}
@override
Future<void> hide() async {
assert(_isOpened, 'The browser is not opened.');
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('hide', args);
}
@override
Future<void> close() async {
assert(_isOpened, 'The browser is not opened.');
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('close', args);
}
@override
Future<bool> isHidden() async {
assert(_isOpened, 'The browser is not opened.');
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('isHidden', args) ?? false;
}
@override
@Deprecated('Use setSettings instead')
Future<void> setOptions({required InAppBrowserClassOptions options}) async {
assert(_isOpened, 'The browser is not opened.');
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('settings', () => options.toMap());
await channel?.invokeMethod('setSettings', args);
}
@override
@Deprecated('Use getSettings instead')
Future<InAppBrowserClassOptions?> getOptions() async {
assert(_isOpened, 'The browser is not opened.');
Map<String, dynamic> args = <String, dynamic>{};
Map<dynamic, dynamic>? options =
await channel?.invokeMethod('getSettings', args);
if (options != null) {
options = options.cast<String, dynamic>();
return InAppBrowserClassOptions.fromMap(options as Map<String, dynamic>);
}
return null;
}
@override
Future<void> setSettings(
{required InAppBrowserClassSettings settings}) async {
assert(_isOpened, 'The browser is not opened.');
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('settings', () => settings.toMap());
await channel?.invokeMethod('setSettings', args);
}
@override
Future<InAppBrowserClassSettings?> getSettings() async {
assert(_isOpened, 'The browser is not opened.');
Map<String, dynamic> args = <String, dynamic>{};
Map<dynamic, dynamic>? settings =
await channel?.invokeMethod('getSettings', args);
if (settings != null) {
settings = settings.cast<String, dynamic>();
return InAppBrowserClassSettings.fromMap(
settings as Map<String, dynamic>);
}
return null;
}
@override
bool isOpened() {
return this._isOpened;
}
@override
@mustCallSuper
void dispose() {
super.dispose();
disposeChannel();
_webViewController?.dispose();
_webViewController = null;
pullToRefreshController?.dispose();
findInteractionController?.dispose();
}
}
extension InternalInAppBrowser on IOSInAppBrowser {
void setContextMenu(ContextMenu? contextMenu) {
_contextMenu = contextMenu;
}
}
@@ -0,0 +1 @@
export 'in_app_browser.dart' hide InternalInAppBrowser;
@@ -0,0 +1,4 @@
import 'package:flutter/services.dart';
const IN_APP_WEBVIEW_STATIC_CHANNEL =
MethodChannel('com.pichillilorenzo/flutter_inappwebview_manager');
@@ -0,0 +1,439 @@
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import '../find_interaction/find_interaction_controller.dart';
import '../pull_to_refresh/pull_to_refresh_controller.dart';
import 'in_app_webview_controller.dart';
/// Object specifying creation parameters for creating a [IOSHeadlessInAppWebView].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformHeadlessInAppWebViewCreationParams] for
/// more information.
@immutable
class IOSHeadlessInAppWebViewCreationParams
extends PlatformHeadlessInAppWebViewCreationParams {
/// Creates a new [IOSHeadlessInAppWebViewCreationParams] instance.
IOSHeadlessInAppWebViewCreationParams(
{super.controllerFromPlatform,
super.initialSize,
super.windowId,
super.onWebViewCreated,
super.onLoadStart,
super.onLoadStop,
@Deprecated('Use onReceivedError instead') super.onLoadError,
super.onReceivedError,
@Deprecated("Use onReceivedHttpError instead") super.onLoadHttpError,
super.onReceivedHttpError,
super.onProgressChanged,
super.onConsoleMessage,
super.shouldOverrideUrlLoading,
super.onLoadResource,
super.onScrollChanged,
@Deprecated('Use onDownloadStartRequest instead') super.onDownloadStart,
super.onDownloadStartRequest,
@Deprecated('Use onLoadResourceWithCustomScheme instead')
super.onLoadResourceCustomScheme,
super.onLoadResourceWithCustomScheme,
super.onCreateWindow,
super.onCloseWindow,
super.onJsAlert,
super.onJsConfirm,
super.onJsPrompt,
super.onReceivedHttpAuthRequest,
super.onReceivedServerTrustAuthRequest,
super.onReceivedClientCertRequest,
@Deprecated('Use FindInteractionController.onFindResultReceived instead')
super.onFindResultReceived,
super.shouldInterceptAjaxRequest,
super.onAjaxReadyStateChange,
super.onAjaxProgress,
super.shouldInterceptFetchRequest,
super.onUpdateVisitedHistory,
@Deprecated("Use onPrintRequest instead") super.onPrint,
super.onPrintRequest,
super.onLongPressHitTestResult,
super.onEnterFullscreen,
super.onExitFullscreen,
super.onPageCommitVisible,
super.onTitleChanged,
super.onWindowFocus,
super.onWindowBlur,
super.onOverScrolled,
super.onZoomScaleChanged,
@Deprecated('Use onSafeBrowsingHit instead')
super.androidOnSafeBrowsingHit,
super.onSafeBrowsingHit,
@Deprecated('Use onPermissionRequest instead')
super.androidOnPermissionRequest,
super.onPermissionRequest,
@Deprecated('Use onGeolocationPermissionsShowPrompt instead')
super.androidOnGeolocationPermissionsShowPrompt,
super.onGeolocationPermissionsShowPrompt,
@Deprecated('Use onGeolocationPermissionsHidePrompt instead')
super.androidOnGeolocationPermissionsHidePrompt,
super.onGeolocationPermissionsHidePrompt,
@Deprecated('Use shouldInterceptRequest instead')
super.androidShouldInterceptRequest,
super.shouldInterceptRequest,
@Deprecated('Use onRenderProcessGone instead')
super.androidOnRenderProcessGone,
super.onRenderProcessGone,
@Deprecated('Use onRenderProcessResponsive instead')
super.androidOnRenderProcessResponsive,
super.onRenderProcessResponsive,
@Deprecated('Use onRenderProcessUnresponsive instead')
super.androidOnRenderProcessUnresponsive,
super.onRenderProcessUnresponsive,
@Deprecated('Use onFormResubmission instead')
super.androidOnFormResubmission,
super.onFormResubmission,
@Deprecated('Use onZoomScaleChanged instead') super.androidOnScaleChanged,
@Deprecated('Use onReceivedIcon instead') super.androidOnReceivedIcon,
super.onReceivedIcon,
@Deprecated('Use onReceivedTouchIconUrl instead')
super.androidOnReceivedTouchIconUrl,
super.onReceivedTouchIconUrl,
@Deprecated('Use onJsBeforeUnload instead') super.androidOnJsBeforeUnload,
super.onJsBeforeUnload,
@Deprecated('Use onReceivedLoginRequest instead')
super.androidOnReceivedLoginRequest,
super.onReceivedLoginRequest,
super.onPermissionRequestCanceled,
super.onRequestFocus,
@Deprecated('Use onWebContentProcessDidTerminate instead')
super.iosOnWebContentProcessDidTerminate,
super.onWebContentProcessDidTerminate,
@Deprecated(
'Use onDidReceiveServerRedirectForProvisionalNavigation instead')
super.iosOnDidReceiveServerRedirectForProvisionalNavigation,
super.onDidReceiveServerRedirectForProvisionalNavigation,
@Deprecated('Use onNavigationResponse instead')
super.iosOnNavigationResponse,
super.onNavigationResponse,
@Deprecated('Use shouldAllowDeprecatedTLS instead')
super.iosShouldAllowDeprecatedTLS,
super.shouldAllowDeprecatedTLS,
super.onCameraCaptureStateChanged,
super.onMicrophoneCaptureStateChanged,
super.onContentSizeChanged,
super.initialUrlRequest,
super.initialFile,
super.initialData,
@Deprecated('Use initialSettings instead') super.initialOptions,
super.initialSettings,
super.contextMenu,
super.initialUserScripts,
this.pullToRefreshController,
this.findInteractionController});
/// Creates a [IOSHeadlessInAppWebViewCreationParams] instance based on [PlatformHeadlessInAppWebViewCreationParams].
IOSHeadlessInAppWebViewCreationParams.fromPlatformHeadlessInAppWebViewCreationParams(
PlatformHeadlessInAppWebViewCreationParams params)
: this(
controllerFromPlatform: params.controllerFromPlatform,
initialSize: params.initialSize,
windowId: params.windowId,
onWebViewCreated: params.onWebViewCreated,
onLoadStart: params.onLoadStart,
onLoadStop: params.onLoadStop,
onLoadError: params.onLoadError,
onReceivedError: params.onReceivedError,
onLoadHttpError: params.onLoadHttpError,
onReceivedHttpError: params.onReceivedHttpError,
onProgressChanged: params.onProgressChanged,
onConsoleMessage: params.onConsoleMessage,
shouldOverrideUrlLoading: params.shouldOverrideUrlLoading,
onLoadResource: params.onLoadResource,
onScrollChanged: params.onScrollChanged,
onDownloadStart: params.onDownloadStart,
onDownloadStartRequest: params.onDownloadStartRequest,
onLoadResourceCustomScheme: params.onLoadResourceCustomScheme,
onLoadResourceWithCustomScheme:
params.onLoadResourceWithCustomScheme,
onCreateWindow: params.onCreateWindow,
onCloseWindow: params.onCloseWindow,
onJsAlert: params.onJsAlert,
onJsConfirm: params.onJsConfirm,
onJsPrompt: params.onJsPrompt,
onReceivedHttpAuthRequest: params.onReceivedHttpAuthRequest,
onReceivedServerTrustAuthRequest:
params.onReceivedServerTrustAuthRequest,
onReceivedClientCertRequest: params.onReceivedClientCertRequest,
onFindResultReceived: params.onFindResultReceived,
shouldInterceptAjaxRequest: params.shouldInterceptAjaxRequest,
onAjaxReadyStateChange: params.onAjaxReadyStateChange,
onAjaxProgress: params.onAjaxProgress,
shouldInterceptFetchRequest: params.shouldInterceptFetchRequest,
onUpdateVisitedHistory: params.onUpdateVisitedHistory,
onPrint: params.onPrint,
onPrintRequest: params.onPrintRequest,
onLongPressHitTestResult: params.onLongPressHitTestResult,
onEnterFullscreen: params.onEnterFullscreen,
onExitFullscreen: params.onExitFullscreen,
onPageCommitVisible: params.onPageCommitVisible,
onTitleChanged: params.onTitleChanged,
onWindowFocus: params.onWindowFocus,
onWindowBlur: params.onWindowBlur,
onOverScrolled: params.onOverScrolled,
onZoomScaleChanged: params.onZoomScaleChanged,
androidOnSafeBrowsingHit: params.androidOnSafeBrowsingHit,
onSafeBrowsingHit: params.onSafeBrowsingHit,
androidOnPermissionRequest: params.androidOnPermissionRequest,
onPermissionRequest: params.onPermissionRequest,
androidOnGeolocationPermissionsShowPrompt:
params.androidOnGeolocationPermissionsShowPrompt,
onGeolocationPermissionsShowPrompt:
params.onGeolocationPermissionsShowPrompt,
androidOnGeolocationPermissionsHidePrompt:
params.androidOnGeolocationPermissionsHidePrompt,
onGeolocationPermissionsHidePrompt:
params.onGeolocationPermissionsHidePrompt,
androidShouldInterceptRequest: params.androidShouldInterceptRequest,
shouldInterceptRequest: params.shouldInterceptRequest,
androidOnRenderProcessGone: params.androidOnRenderProcessGone,
onRenderProcessGone: params.onRenderProcessGone,
androidOnRenderProcessResponsive:
params.androidOnRenderProcessResponsive,
onRenderProcessResponsive: params.onRenderProcessResponsive,
androidOnRenderProcessUnresponsive:
params.androidOnRenderProcessUnresponsive,
onRenderProcessUnresponsive: params.onRenderProcessUnresponsive,
androidOnFormResubmission: params.androidOnFormResubmission,
onFormResubmission: params.onFormResubmission,
androidOnScaleChanged: params.androidOnScaleChanged,
androidOnReceivedIcon: params.androidOnReceivedIcon,
onReceivedIcon: params.onReceivedIcon,
androidOnReceivedTouchIconUrl: params.androidOnReceivedTouchIconUrl,
onReceivedTouchIconUrl: params.onReceivedTouchIconUrl,
androidOnJsBeforeUnload: params.androidOnJsBeforeUnload,
onJsBeforeUnload: params.onJsBeforeUnload,
androidOnReceivedLoginRequest: params.androidOnReceivedLoginRequest,
onReceivedLoginRequest: params.onReceivedLoginRequest,
onPermissionRequestCanceled: params.onPermissionRequestCanceled,
onRequestFocus: params.onRequestFocus,
iosOnWebContentProcessDidTerminate:
params.iosOnWebContentProcessDidTerminate,
onWebContentProcessDidTerminate:
params.onWebContentProcessDidTerminate,
iosOnDidReceiveServerRedirectForProvisionalNavigation:
params.iosOnDidReceiveServerRedirectForProvisionalNavigation,
onDidReceiveServerRedirectForProvisionalNavigation:
params.onDidReceiveServerRedirectForProvisionalNavigation,
iosOnNavigationResponse: params.iosOnNavigationResponse,
onNavigationResponse: params.onNavigationResponse,
iosShouldAllowDeprecatedTLS: params.iosShouldAllowDeprecatedTLS,
shouldAllowDeprecatedTLS: params.shouldAllowDeprecatedTLS,
onCameraCaptureStateChanged: params.onCameraCaptureStateChanged,
onMicrophoneCaptureStateChanged:
params.onMicrophoneCaptureStateChanged,
onContentSizeChanged: params.onContentSizeChanged,
initialUrlRequest: params.initialUrlRequest,
initialFile: params.initialFile,
initialData: params.initialData,
initialOptions: params.initialOptions,
initialSettings: params.initialSettings,
contextMenu: params.contextMenu,
initialUserScripts: params.initialUserScripts,
pullToRefreshController:
params.pullToRefreshController as IOSPullToRefreshController?,
findInteractionController: params.findInteractionController
as IOSFindInteractionController?);
@override
final IOSFindInteractionController? findInteractionController;
@override
final IOSPullToRefreshController? pullToRefreshController;
}
///{@macro flutter_inappwebview_platform_interface.PlatformHeadlessInAppWebView}
class IOSHeadlessInAppWebView extends PlatformHeadlessInAppWebView
with ChannelController {
@override
late final String id;
bool _started = false;
bool _running = false;
static const MethodChannel _sharedChannel =
const MethodChannel('com.pichillilorenzo/flutter_headless_inappwebview');
IOSInAppWebViewController? _webViewController;
/// Constructs a [IOSHeadlessInAppWebView].
IOSHeadlessInAppWebView(PlatformHeadlessInAppWebViewCreationParams params)
: super.implementation(
params is IOSHeadlessInAppWebViewCreationParams
? params
: IOSHeadlessInAppWebViewCreationParams
.fromPlatformHeadlessInAppWebViewCreationParams(params),
) {
id = IdGenerator.generate();
}
@override
IOSInAppWebViewController? get webViewController => _webViewController;
dynamic _controllerFromPlatform;
IOSHeadlessInAppWebViewCreationParams get _iosParams =>
params as IOSHeadlessInAppWebViewCreationParams;
_init() {
_webViewController = IOSInAppWebViewController(
IOSInAppWebViewControllerCreationParams(id: id, webviewParams: params),
);
_controllerFromPlatform =
params.controllerFromPlatform?.call(_webViewController!) ??
_webViewController!;
_iosParams.pullToRefreshController?.init(id);
_iosParams.findInteractionController?.init(id);
channel =
MethodChannel('com.pichillilorenzo/flutter_headless_inappwebview_$id');
handler = _handleMethod;
initMethodCallHandler();
}
Future<dynamic> _handleMethod(MethodCall call) async {
switch (call.method) {
case "onWebViewCreated":
if (params.onWebViewCreated != null && _webViewController != null) {
params.onWebViewCreated!(_controllerFromPlatform);
}
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
return null;
}
Future<void> run() async {
if (_started) {
return;
}
_started = true;
_init();
final initialSettings = params.initialSettings ?? InAppWebViewSettings();
_inferInitialSettings(initialSettings);
Map<String, dynamic> settingsMap =
(params.initialSettings != null ? initialSettings.toMap() : null) ??
params.initialOptions?.toMap() ??
initialSettings.toMap();
Map<String, dynamic> pullToRefreshSettings =
_iosParams.pullToRefreshController?.params.settings.toMap() ??
_iosParams.pullToRefreshController?.params.options.toMap() ??
PullToRefreshSettings(enabled: false).toMap();
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('id', () => id);
args.putIfAbsent(
'params',
() => <String, dynamic>{
'initialUrlRequest': params.initialUrlRequest?.toMap(),
'initialFile': params.initialFile,
'initialData': params.initialData?.toMap(),
'initialSettings': settingsMap,
'contextMenu': params.contextMenu?.toMap() ?? {},
'windowId': params.windowId,
'initialUserScripts':
params.initialUserScripts?.map((e) => e.toMap()).toList() ??
[],
'pullToRefreshSettings': pullToRefreshSettings,
'initialSize': params.initialSize.toMap()
});
await _sharedChannel.invokeMethod('run', args);
_running = true;
}
void _inferInitialSettings(InAppWebViewSettings settings) {
if (params.shouldOverrideUrlLoading != null &&
settings.useShouldOverrideUrlLoading == null) {
settings.useShouldOverrideUrlLoading = true;
}
if (params.onLoadResource != null && settings.useOnLoadResource == null) {
settings.useOnLoadResource = true;
}
if (params.onDownloadStartRequest != null &&
settings.useOnDownloadStart == null) {
settings.useOnDownloadStart = true;
}
if (params.shouldInterceptAjaxRequest != null &&
settings.useShouldInterceptAjaxRequest == null) {
settings.useShouldInterceptAjaxRequest = true;
}
if (params.shouldInterceptFetchRequest != null &&
settings.useShouldInterceptFetchRequest == null) {
settings.useShouldInterceptFetchRequest = true;
}
if (params.shouldInterceptRequest != null &&
settings.useShouldInterceptRequest == null) {
settings.useShouldInterceptRequest = true;
}
if (params.onRenderProcessGone != null &&
settings.useOnRenderProcessGone == null) {
settings.useOnRenderProcessGone = true;
}
if (params.onNavigationResponse != null &&
settings.useOnNavigationResponse == null) {
settings.useOnNavigationResponse = true;
}
}
@override
bool isRunning() {
return _running;
}
@override
Future<void> setSize(Size size) async {
if (!_running) {
return;
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('size', () => size.toMap());
await channel?.invokeMethod('setSize', args);
}
@override
Future<Size?> getSize() async {
if (!_running) {
return null;
}
Map<String, dynamic> args = <String, dynamic>{};
Map<String, dynamic> sizeMap =
(await channel?.invokeMethod('getSize', args))?.cast<String, dynamic>();
return MapSize.fromMap(sizeMap);
}
@override
Future<void> dispose() async {
if (!_running) {
return;
}
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('dispose', args);
disposeChannel();
_started = false;
_running = false;
_webViewController?.dispose();
_webViewController = null;
_controllerFromPlatform = null;
_iosParams.pullToRefreshController?.dispose();
_iosParams.findInteractionController?.dispose();
}
}
extension InternalHeadlessInAppWebView on IOSHeadlessInAppWebView {
Future<void> internalDispose() async {
_started = false;
_running = false;
}
}
@@ -0,0 +1,416 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'headless_in_app_webview.dart';
import '../find_interaction/find_interaction_controller.dart';
import 'in_app_webview_controller.dart';
import '../pull_to_refresh/main.dart';
import '../pull_to_refresh/pull_to_refresh_controller.dart';
/// Object specifying creation parameters for creating a [PlatformInAppWebViewWidget].
///
/// Platform specific implementations can add additional fields by extending
/// this class.
class IOSInAppWebViewWidgetCreationParams
extends PlatformInAppWebViewWidgetCreationParams {
IOSInAppWebViewWidgetCreationParams(
{super.controllerFromPlatform,
super.key,
super.layoutDirection,
super.gestureRecognizers,
super.headlessWebView,
super.keepAlive,
super.preventGestureDelay,
super.windowId,
super.onWebViewCreated,
super.onLoadStart,
super.onLoadStop,
@Deprecated('Use onReceivedError instead') super.onLoadError,
super.onReceivedError,
@Deprecated("Use onReceivedHttpError instead") super.onLoadHttpError,
super.onReceivedHttpError,
super.onProgressChanged,
super.onConsoleMessage,
super.shouldOverrideUrlLoading,
super.onLoadResource,
super.onScrollChanged,
@Deprecated('Use onDownloadStartRequest instead') super.onDownloadStart,
super.onDownloadStartRequest,
@Deprecated('Use onLoadResourceWithCustomScheme instead')
super.onLoadResourceCustomScheme,
super.onLoadResourceWithCustomScheme,
super.onCreateWindow,
super.onCloseWindow,
super.onJsAlert,
super.onJsConfirm,
super.onJsPrompt,
super.onReceivedHttpAuthRequest,
super.onReceivedServerTrustAuthRequest,
super.onReceivedClientCertRequest,
@Deprecated('Use FindInteractionController.onFindResultReceived instead')
super.onFindResultReceived,
super.shouldInterceptAjaxRequest,
super.onAjaxReadyStateChange,
super.onAjaxProgress,
super.shouldInterceptFetchRequest,
super.onUpdateVisitedHistory,
@Deprecated("Use onPrintRequest instead") super.onPrint,
super.onPrintRequest,
super.onLongPressHitTestResult,
super.onEnterFullscreen,
super.onExitFullscreen,
super.onPageCommitVisible,
super.onTitleChanged,
super.onWindowFocus,
super.onWindowBlur,
super.onOverScrolled,
super.onZoomScaleChanged,
@Deprecated('Use onSafeBrowsingHit instead')
super.androidOnSafeBrowsingHit,
super.onSafeBrowsingHit,
@Deprecated('Use onPermissionRequest instead')
super.androidOnPermissionRequest,
super.onPermissionRequest,
@Deprecated('Use onGeolocationPermissionsShowPrompt instead')
super.androidOnGeolocationPermissionsShowPrompt,
super.onGeolocationPermissionsShowPrompt,
@Deprecated('Use onGeolocationPermissionsHidePrompt instead')
super.androidOnGeolocationPermissionsHidePrompt,
super.onGeolocationPermissionsHidePrompt,
@Deprecated('Use shouldInterceptRequest instead')
super.androidShouldInterceptRequest,
super.shouldInterceptRequest,
@Deprecated('Use onRenderProcessGone instead')
super.androidOnRenderProcessGone,
super.onRenderProcessGone,
@Deprecated('Use onRenderProcessResponsive instead')
super.androidOnRenderProcessResponsive,
super.onRenderProcessResponsive,
@Deprecated('Use onRenderProcessUnresponsive instead')
super.androidOnRenderProcessUnresponsive,
super.onRenderProcessUnresponsive,
@Deprecated('Use onFormResubmission instead')
super.androidOnFormResubmission,
super.onFormResubmission,
@Deprecated('Use onZoomScaleChanged instead') super.androidOnScaleChanged,
@Deprecated('Use onReceivedIcon instead') super.androidOnReceivedIcon,
super.onReceivedIcon,
@Deprecated('Use onReceivedTouchIconUrl instead')
super.androidOnReceivedTouchIconUrl,
super.onReceivedTouchIconUrl,
@Deprecated('Use onJsBeforeUnload instead') super.androidOnJsBeforeUnload,
super.onJsBeforeUnload,
@Deprecated('Use onReceivedLoginRequest instead')
super.androidOnReceivedLoginRequest,
super.onReceivedLoginRequest,
super.onPermissionRequestCanceled,
super.onRequestFocus,
@Deprecated('Use onWebContentProcessDidTerminate instead')
super.iosOnWebContentProcessDidTerminate,
super.onWebContentProcessDidTerminate,
@Deprecated(
'Use onDidReceiveServerRedirectForProvisionalNavigation instead')
super.iosOnDidReceiveServerRedirectForProvisionalNavigation,
super.onDidReceiveServerRedirectForProvisionalNavigation,
@Deprecated('Use onNavigationResponse instead')
super.iosOnNavigationResponse,
super.onNavigationResponse,
@Deprecated('Use shouldAllowDeprecatedTLS instead')
super.iosShouldAllowDeprecatedTLS,
super.shouldAllowDeprecatedTLS,
super.onCameraCaptureStateChanged,
super.onMicrophoneCaptureStateChanged,
super.onContentSizeChanged,
super.initialUrlRequest,
super.initialFile,
super.initialData,
@Deprecated('Use initialSettings instead') super.initialOptions,
super.initialSettings,
super.contextMenu,
super.initialUserScripts,
this.pullToRefreshController,
this.findInteractionController});
/// Constructs a [IOSInAppWebViewWidgetCreationParams] using a
/// [PlatformInAppWebViewWidgetCreationParams].
IOSInAppWebViewWidgetCreationParams.fromPlatformInAppWebViewWidgetCreationParams(
PlatformInAppWebViewWidgetCreationParams params)
: this(
controllerFromPlatform: params.controllerFromPlatform,
key: params.key,
layoutDirection: params.layoutDirection,
gestureRecognizers: params.gestureRecognizers,
headlessWebView: params.headlessWebView,
keepAlive: params.keepAlive,
preventGestureDelay: params.preventGestureDelay,
windowId: params.windowId,
onWebViewCreated: params.onWebViewCreated,
onLoadStart: params.onLoadStart,
onLoadStop: params.onLoadStop,
onLoadError: params.onLoadError,
onReceivedError: params.onReceivedError,
onLoadHttpError: params.onLoadHttpError,
onReceivedHttpError: params.onReceivedHttpError,
onProgressChanged: params.onProgressChanged,
onConsoleMessage: params.onConsoleMessage,
shouldOverrideUrlLoading: params.shouldOverrideUrlLoading,
onLoadResource: params.onLoadResource,
onScrollChanged: params.onScrollChanged,
onDownloadStart: params.onDownloadStart,
onDownloadStartRequest: params.onDownloadStartRequest,
onLoadResourceCustomScheme: params.onLoadResourceCustomScheme,
onLoadResourceWithCustomScheme:
params.onLoadResourceWithCustomScheme,
onCreateWindow: params.onCreateWindow,
onCloseWindow: params.onCloseWindow,
onJsAlert: params.onJsAlert,
onJsConfirm: params.onJsConfirm,
onJsPrompt: params.onJsPrompt,
onReceivedHttpAuthRequest: params.onReceivedHttpAuthRequest,
onReceivedServerTrustAuthRequest:
params.onReceivedServerTrustAuthRequest,
onReceivedClientCertRequest: params.onReceivedClientCertRequest,
onFindResultReceived: params.onFindResultReceived,
shouldInterceptAjaxRequest: params.shouldInterceptAjaxRequest,
onAjaxReadyStateChange: params.onAjaxReadyStateChange,
onAjaxProgress: params.onAjaxProgress,
shouldInterceptFetchRequest: params.shouldInterceptFetchRequest,
onUpdateVisitedHistory: params.onUpdateVisitedHistory,
onPrint: params.onPrint,
onPrintRequest: params.onPrintRequest,
onLongPressHitTestResult: params.onLongPressHitTestResult,
onEnterFullscreen: params.onEnterFullscreen,
onExitFullscreen: params.onExitFullscreen,
onPageCommitVisible: params.onPageCommitVisible,
onTitleChanged: params.onTitleChanged,
onWindowFocus: params.onWindowFocus,
onWindowBlur: params.onWindowBlur,
onOverScrolled: params.onOverScrolled,
onZoomScaleChanged: params.onZoomScaleChanged,
androidOnSafeBrowsingHit: params.androidOnSafeBrowsingHit,
onSafeBrowsingHit: params.onSafeBrowsingHit,
androidOnPermissionRequest: params.androidOnPermissionRequest,
onPermissionRequest: params.onPermissionRequest,
androidOnGeolocationPermissionsShowPrompt:
params.androidOnGeolocationPermissionsShowPrompt,
onGeolocationPermissionsShowPrompt:
params.onGeolocationPermissionsShowPrompt,
androidOnGeolocationPermissionsHidePrompt:
params.androidOnGeolocationPermissionsHidePrompt,
onGeolocationPermissionsHidePrompt:
params.onGeolocationPermissionsHidePrompt,
androidShouldInterceptRequest: params.androidShouldInterceptRequest,
shouldInterceptRequest: params.shouldInterceptRequest,
androidOnRenderProcessGone: params.androidOnRenderProcessGone,
onRenderProcessGone: params.onRenderProcessGone,
androidOnRenderProcessResponsive:
params.androidOnRenderProcessResponsive,
onRenderProcessResponsive: params.onRenderProcessResponsive,
androidOnRenderProcessUnresponsive:
params.androidOnRenderProcessUnresponsive,
onRenderProcessUnresponsive: params.onRenderProcessUnresponsive,
androidOnFormResubmission: params.androidOnFormResubmission,
onFormResubmission: params.onFormResubmission,
androidOnScaleChanged: params.androidOnScaleChanged,
androidOnReceivedIcon: params.androidOnReceivedIcon,
onReceivedIcon: params.onReceivedIcon,
androidOnReceivedTouchIconUrl: params.androidOnReceivedTouchIconUrl,
onReceivedTouchIconUrl: params.onReceivedTouchIconUrl,
androidOnJsBeforeUnload: params.androidOnJsBeforeUnload,
onJsBeforeUnload: params.onJsBeforeUnload,
androidOnReceivedLoginRequest: params.androidOnReceivedLoginRequest,
onReceivedLoginRequest: params.onReceivedLoginRequest,
onPermissionRequestCanceled: params.onPermissionRequestCanceled,
onRequestFocus: params.onRequestFocus,
iosOnWebContentProcessDidTerminate:
params.iosOnWebContentProcessDidTerminate,
onWebContentProcessDidTerminate:
params.onWebContentProcessDidTerminate,
iosOnDidReceiveServerRedirectForProvisionalNavigation:
params.iosOnDidReceiveServerRedirectForProvisionalNavigation,
onDidReceiveServerRedirectForProvisionalNavigation:
params.onDidReceiveServerRedirectForProvisionalNavigation,
iosOnNavigationResponse: params.iosOnNavigationResponse,
onNavigationResponse: params.onNavigationResponse,
iosShouldAllowDeprecatedTLS: params.iosShouldAllowDeprecatedTLS,
shouldAllowDeprecatedTLS: params.shouldAllowDeprecatedTLS,
onCameraCaptureStateChanged: params.onCameraCaptureStateChanged,
onMicrophoneCaptureStateChanged:
params.onMicrophoneCaptureStateChanged,
onContentSizeChanged: params.onContentSizeChanged,
initialUrlRequest: params.initialUrlRequest,
initialFile: params.initialFile,
initialData: params.initialData,
initialOptions: params.initialOptions,
initialSettings: params.initialSettings,
contextMenu: params.contextMenu,
initialUserScripts: params.initialUserScripts,
pullToRefreshController:
params.pullToRefreshController as IOSPullToRefreshController?,
findInteractionController: params.findInteractionController
as IOSFindInteractionController?);
@override
final IOSFindInteractionController? findInteractionController;
@override
final IOSPullToRefreshController? pullToRefreshController;
}
///{@macro flutter_inappwebview_platform_interface.PlatformInAppWebViewWidget}
class IOSInAppWebViewWidget extends PlatformInAppWebViewWidget {
/// Constructs a [IOSInAppWebViewWidget].
///
///{@macro flutter_inappwebview_platform_interface.PlatformInAppWebViewWidget}
IOSInAppWebViewWidget(PlatformInAppWebViewWidgetCreationParams params)
: super.implementation(
params is IOSInAppWebViewWidgetCreationParams
? params
: IOSInAppWebViewWidgetCreationParams
.fromPlatformInAppWebViewWidgetCreationParams(params),
);
IOSInAppWebViewWidgetCreationParams get _iosParams =>
params as IOSInAppWebViewWidgetCreationParams;
IOSInAppWebViewController? _controller;
IOSHeadlessInAppWebView? get _iosHeadlessInAppWebView =>
params.headlessWebView as IOSHeadlessInAppWebView?;
@override
Widget build(BuildContext context) {
final initialSettings = params.initialSettings ?? InAppWebViewSettings();
_inferInitialSettings(initialSettings);
Map<String, dynamic> settingsMap =
(params.initialSettings != null ? initialSettings.toMap() : null) ??
// ignore: deprecated_member_use_from_same_package
params.initialOptions?.toMap() ??
initialSettings.toMap();
Map<String, dynamic> pullToRefreshSettings =
params.pullToRefreshController?.params.settings.toMap() ??
// ignore: deprecated_member_use_from_same_package
params.pullToRefreshController?.params.options.toMap() ??
PullToRefreshSettings(enabled: false).toMap();
if ((params.headlessWebView?.isRunning() ?? false) &&
params.keepAlive != null) {
final headlessId = params.headlessWebView?.id;
if (headlessId != null) {
// force keep alive id to match headless webview id
params.keepAlive?.id = headlessId;
}
}
return UiKitView(
viewType: 'com.pichillilorenzo/flutter_inappwebview',
onPlatformViewCreated: _onPlatformViewCreated,
gestureRecognizers: params.gestureRecognizers,
creationParams: <String, dynamic>{
'initialUrlRequest': params.initialUrlRequest?.toMap(),
'initialFile': params.initialFile,
'initialData': params.initialData?.toMap(),
'initialSettings': settingsMap,
'contextMenu': params.contextMenu?.toMap() ?? {},
'windowId': params.windowId,
'headlessWebViewId': params.headlessWebView?.isRunning() ?? false
? params.headlessWebView?.id
: null,
'initialUserScripts':
params.initialUserScripts?.map((e) => e.toMap()).toList() ?? [],
'pullToRefreshSettings': pullToRefreshSettings,
'keepAliveId': params.keepAlive?.id,
'preventGestureDelay': params.preventGestureDelay
},
creationParamsCodec: const StandardMessageCodec(),
);
}
void _onPlatformViewCreated(int id) {
dynamic viewId = id;
if (params.headlessWebView?.isRunning() ?? false) {
viewId = params.headlessWebView?.id;
}
viewId = params.keepAlive?.id ?? viewId ?? id;
_iosHeadlessInAppWebView?.internalDispose();
_controller = IOSInAppWebViewController(
PlatformInAppWebViewControllerCreationParams(
id: viewId, webviewParams: params));
_iosParams.pullToRefreshController?.init(viewId);
_iosParams.findInteractionController?.init(viewId);
debugLog(
className: runtimeType.toString(),
id: viewId?.toString(),
debugLoggingSettings:
PlatformInAppWebViewController.debugLoggingSettings,
method: "onWebViewCreated",
args: []);
if (params.onWebViewCreated != null) {
params.onWebViewCreated!(
params.controllerFromPlatform?.call(_controller!) ?? _controller!);
}
}
void _inferInitialSettings(InAppWebViewSettings settings) {
if (params.shouldOverrideUrlLoading != null &&
settings.useShouldOverrideUrlLoading == null) {
settings.useShouldOverrideUrlLoading = true;
}
if (params.onLoadResource != null && settings.useOnLoadResource == null) {
settings.useOnLoadResource = true;
}
if (params.onDownloadStartRequest != null &&
settings.useOnDownloadStart == null) {
settings.useOnDownloadStart = true;
}
if ((params.shouldInterceptAjaxRequest != null ||
params.onAjaxProgress != null ||
params.onAjaxReadyStateChange != null) &&
settings.useShouldInterceptAjaxRequest == null) {
settings.useShouldInterceptAjaxRequest = true;
}
if (params.shouldInterceptFetchRequest != null &&
settings.useShouldInterceptFetchRequest == null) {
settings.useShouldInterceptFetchRequest = true;
}
if (params.shouldInterceptRequest != null &&
settings.useShouldInterceptRequest == null) {
settings.useShouldInterceptRequest = true;
}
if (params.onRenderProcessGone != null &&
settings.useOnRenderProcessGone == null) {
settings.useOnRenderProcessGone = true;
}
if (params.onNavigationResponse != null &&
settings.useOnNavigationResponse == null) {
settings.useOnNavigationResponse = true;
}
}
@override
void dispose() {
dynamic viewId = _controller?.getViewId();
debugLog(
className: runtimeType.toString(),
id: viewId?.toString(),
debugLoggingSettings:
PlatformInAppWebViewController.debugLoggingSettings,
method: "dispose",
args: []);
final isKeepAlive = params.keepAlive != null;
_controller?.dispose(isKeepAlive: isKeepAlive);
_controller = null;
params.pullToRefreshController?.dispose(isKeepAlive: isKeepAlive);
params.findInteractionController?.dispose(isKeepAlive: isKeepAlive);
}
@override
T controllerFromPlatform<T>(PlatformInAppWebViewController controller) {
// unused
throw UnimplementedError();
}
}
@@ -0,0 +1,3 @@
export 'in_app_webview_controller.dart' hide InternalInAppWebViewController;
export 'in_app_webview.dart';
export 'headless_in_app_webview.dart' hide InternalHeadlessInAppWebView;
@@ -0,0 +1,273 @@
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'chrome_safari_browser/chrome_safari_browser.dart';
import 'cookie_manager.dart';
import 'http_auth_credentials_database.dart';
import 'find_interaction/main.dart';
import 'in_app_browser/in_app_browser.dart';
import 'in_app_webview/main.dart';
import 'print_job/main.dart';
import 'pull_to_refresh/main.dart';
import 'web_message/main.dart';
import 'web_storage/main.dart';
import 'web_authentication_session/main.dart';
/// Implementation of [InAppWebViewPlatform] using the WebKit API.
class IOSInAppWebViewPlatform extends InAppWebViewPlatform {
/// Registers this class as the default instance of [InAppWebViewPlatform].
static void registerWith() {
InAppWebViewPlatform.instance = IOSInAppWebViewPlatform();
}
/// Creates a new [IOSCookieManager].
///
/// This function should only be called by the app-facing package.
/// Look at using [CookieManager] in `flutter_inappwebview` instead.
@override
IOSCookieManager createPlatformCookieManager(
PlatformCookieManagerCreationParams params,
) {
return IOSCookieManager(params);
}
/// Creates a new [IOSInAppWebViewController].
///
/// This function should only be called by the app-facing package.
/// Look at using [InAppWebViewController] in `flutter_inappwebview` instead.
@override
IOSInAppWebViewController createPlatformInAppWebViewController(
PlatformInAppWebViewControllerCreationParams params,
) {
return IOSInAppWebViewController(params);
}
/// Creates a new empty [IOSInAppWebViewController] to access static methods.
///
/// This function should only be called by the app-facing package.
/// Look at using [InAppWebViewController] in `flutter_inappwebview` instead.
@override
IOSInAppWebViewController createPlatformInAppWebViewControllerStatic() {
return IOSInAppWebViewController.static();
}
/// Creates a new [IOSInAppWebViewWidget].
///
/// This function should only be called by the app-facing package.
/// Look at using [InAppWebView] in `flutter_inappwebview` instead.
@override
IOSInAppWebViewWidget createPlatformInAppWebViewWidget(
PlatformInAppWebViewWidgetCreationParams params,
) {
return IOSInAppWebViewWidget(params);
}
/// Creates a new [IOSFindInteractionController].
///
/// This function should only be called by the app-facing package.
/// Look at using [FindInteractionController] in `flutter_inappwebview` instead.
@override
IOSFindInteractionController createPlatformFindInteractionController(
PlatformFindInteractionControllerCreationParams params,
) {
return IOSFindInteractionController(params);
}
/// Creates a new [IOSPrintJobController].
///
/// This function should only be called by the app-facing package.
/// Look at using [PrintJobController] in `flutter_inappwebview` instead.
@override
IOSPrintJobController createPlatformPrintJobController(
PlatformPrintJobControllerCreationParams params,
) {
return IOSPrintJobController(params);
}
/// Creates a new [IOSPullToRefreshController].
///
/// This function should only be called by the app-facing package.
/// Look at using [PullToRefreshController] in `flutter_inappwebview` instead.
@override
IOSPullToRefreshController createPlatformPullToRefreshController(
PlatformPullToRefreshControllerCreationParams params,
) {
return IOSPullToRefreshController(params);
}
/// Creates a new [IOSWebMessageChannel].
///
/// This function should only be called by the app-facing package.
/// Look at using [WebMessageChannel] in `flutter_inappwebview` instead.
@override
IOSWebMessageChannel createPlatformWebMessageChannel(
PlatformWebMessageChannelCreationParams params,
) {
return IOSWebMessageChannel(params);
}
/// Creates a new empty [IOSWebMessageChannel] to access static methods.
///
/// This function should only be called by the app-facing package.
/// Look at using [WebMessageChannel] in `flutter_inappwebview` instead.
@override
IOSWebMessageChannel createPlatformWebMessageChannelStatic() {
return IOSWebMessageChannel.static();
}
/// Creates a new [IOSWebMessageListener].
///
/// This function should only be called by the app-facing package.
/// Look at using [WebMessageListener] in `flutter_inappwebview` instead.
@override
IOSWebMessageListener createPlatformWebMessageListener(
PlatformWebMessageListenerCreationParams params,
) {
return IOSWebMessageListener(params);
}
/// Creates a new [IOSJavaScriptReplyProxy].
///
/// This function should only be called by the app-facing package.
/// Look at using [JavaScriptReplyProxy] in `flutter_inappwebview` instead.
@override
IOSJavaScriptReplyProxy createPlatformJavaScriptReplyProxy(
PlatformJavaScriptReplyProxyCreationParams params,
) {
return IOSJavaScriptReplyProxy(params);
}
/// Creates a new [IOSWebMessagePort].
///
/// This function should only be called by the app-facing package.
/// Look at using [WebMessagePort] in `flutter_inappwebview` instead.
@override
IOSWebMessagePort createPlatformWebMessagePort(
PlatformWebMessagePortCreationParams params,
) {
return IOSWebMessagePort(params);
}
/// Creates a new [IOSWebStorage].
///
/// This function should only be called by the app-facing package.
/// Look at using [WebStorage] in `flutter_inappwebview` instead.
@override
IOSWebStorage createPlatformWebStorage(
PlatformWebStorageCreationParams params,
) {
return IOSWebStorage(params);
}
/// Creates a new [IOSLocalStorage].
///
/// This function should only be called by the app-facing package.
/// Look at using [LocalStorage] in `flutter_inappwebview` instead.
@override
IOSLocalStorage createPlatformLocalStorage(
PlatformLocalStorageCreationParams params,
) {
return IOSLocalStorage(params);
}
/// Creates a new [IOSSessionStorage].
///
/// This function should only be called by the app-facing package.
/// Look at using [SessionStorage] in `flutter_inappwebview` instead.
@override
IOSSessionStorage createPlatformSessionStorage(
PlatformSessionStorageCreationParams params,
) {
return IOSSessionStorage(params);
}
/// Creates a new [IOSHeadlessInAppWebView].
///
/// This function should only be called by the app-facing package.
/// Look at using [HeadlessInAppWebView] in `flutter_inappwebview` instead.
@override
IOSHeadlessInAppWebView createPlatformHeadlessInAppWebView(
PlatformHeadlessInAppWebViewCreationParams params,
) {
return IOSHeadlessInAppWebView(params);
}
/// Creates a new [IOSHttpAuthCredentialDatabase].
///
/// This function should only be called by the app-facing package.
/// Look at using [HttpAuthCredentialDatabase] in `flutter_inappwebview` instead.
@override
IOSHttpAuthCredentialDatabase createPlatformHttpAuthCredentialDatabase(
PlatformHttpAuthCredentialDatabaseCreationParams params,
) {
return IOSHttpAuthCredentialDatabase(params);
}
/// Creates a new [IOSInAppBrowser].
///
/// This function should only be called by the app-facing package.
/// Look at using [InAppBrowser] in `flutter_inappwebview` instead.
@override
IOSInAppBrowser createPlatformInAppBrowser(
PlatformInAppBrowserCreationParams params,
) {
return IOSInAppBrowser(params);
}
/// Creates a new empty [IOSInAppBrowser] to access static methods.
///
/// This function should only be called by the app-facing package.
/// Look at using [InAppBrowser] in `flutter_inappwebview` instead.
@override
IOSInAppBrowser createPlatformInAppBrowserStatic() {
return IOSInAppBrowser.static();
}
/// Creates a new [IOSChromeSafariBrowser].
///
/// This function should only be called by the app-facing package.
/// Look at using [ChromeSafariBrowser] in `flutter_inappwebview` instead.
@override
IOSChromeSafariBrowser createPlatformChromeSafariBrowser(
PlatformChromeSafariBrowserCreationParams params,
) {
return IOSChromeSafariBrowser(params);
}
/// Creates a new empty [IOSChromeSafariBrowser] to access static methods.
///
/// This function should only be called by the app-facing package.
/// Look at using [ChromeSafariBrowser] in `flutter_inappwebview` instead.
@override
IOSChromeSafariBrowser createPlatformChromeSafariBrowserStatic() {
return IOSChromeSafariBrowser.static();
}
/// Creates a new empty [IOSWebStorageManager] to access static methods.
///
/// This function should only be called by the app-facing package.
/// Look at using [WebStorageManager] in `flutter_inappwebview` instead.
@override
IOSWebStorageManager createPlatformWebStorageManager(
PlatformWebStorageManagerCreationParams params) {
return IOSWebStorageManager(params);
}
/// Creates a new [IOSWebAuthenticationSession].
///
/// This function should only be called by the app-facing package.
/// Look at using [WebAuthenticationSession] in `flutter_inappwebview` instead.
@override
IOSWebAuthenticationSession createPlatformWebAuthenticationSession(
PlatformWebAuthenticationSessionCreationParams params) {
return IOSWebAuthenticationSession(params);
}
/// Creates a new empty [IOSWebAuthenticationSession] to access static methods.
///
/// This function should only be called by the app-facing package.
/// Look at using [WebAuthenticationSession] in `flutter_inappwebview` instead.
@override
IOSWebAuthenticationSession createPlatformWebAuthenticationSessionStatic() {
return IOSWebAuthenticationSession.static();
}
}
@@ -0,0 +1,13 @@
export 'inappwebview_platform.dart';
export 'in_app_webview/main.dart';
export 'in_app_browser/main.dart';
export 'chrome_safari_browser/main.dart';
export 'web_storage/main.dart';
export 'cookie_manager.dart' hide InternalCookieManager;
export 'http_auth_credentials_database.dart'
hide InternalHttpAuthCredentialDatabase;
export 'pull_to_refresh/main.dart';
export 'web_message/main.dart';
export 'print_job/main.dart';
export 'find_interaction/main.dart';
export 'web_authentication_session/main.dart';
@@ -0,0 +1,64 @@
import 'package:flutter/services.dart';
///Platform native utilities
class PlatformUtil {
static PlatformUtil? _instance;
static const MethodChannel _channel =
MethodChannel('com.pichillilorenzo/flutter_inappwebview_platformutil');
PlatformUtil._();
///Get [PlatformUtil] instance.
static PlatformUtil instance() {
return (_instance != null) ? _instance! : _init();
}
static PlatformUtil _init() {
_channel.setMethodCallHandler((call) async {
try {
return await _handleMethod(call);
} on Error catch (e) {
print(e);
print(e.stackTrace);
}
});
_instance = PlatformUtil._();
return _instance!;
}
static Future<dynamic> _handleMethod(MethodCall call) async {}
String? _cachedSystemVersion;
///Get current platform system version.
Future<String> getSystemVersion() async {
if (_cachedSystemVersion != null) {
return _cachedSystemVersion!;
}
Map<String, dynamic> args = <String, dynamic>{};
_cachedSystemVersion =
await _channel.invokeMethod('getSystemVersion', args);
return _cachedSystemVersion!;
}
///Format date.
Future<String> formatDate(
{required DateTime date,
required String format,
String locale = "en_US",
String timezone = "UTC"}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('date', () => date.millisecondsSinceEpoch);
args.putIfAbsent('format', () => format);
args.putIfAbsent('locale', () => locale);
args.putIfAbsent('timezone', () => timezone);
return await _channel.invokeMethod('formatDate', args);
}
///Get cookie expiration date used by Web platform.
Future<String> getWebCookieExpirationDate({required DateTime date}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('date', () => date.millisecondsSinceEpoch);
return await _channel.invokeMethod('getWebCookieExpirationDate', args);
}
}
@@ -0,0 +1 @@
export 'print_job_controller.dart';
@@ -0,0 +1,80 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
/// Object specifying creation parameters for creating a [IOSPrintJobController].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformPrintJobControllerCreationParams] for
/// more information.
@immutable
class IOSPrintJobControllerCreationParams
extends PlatformPrintJobControllerCreationParams {
/// Creates a new [IOSPrintJobControllerCreationParams] instance.
const IOSPrintJobControllerCreationParams(
{required super.id, super.onComplete});
/// Creates a [IOSPrintJobControllerCreationParams] instance based on [PlatformPrintJobControllerCreationParams].
factory IOSPrintJobControllerCreationParams.fromPlatformPrintJobControllerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformPrintJobControllerCreationParams params) {
return IOSPrintJobControllerCreationParams(
id: params.id, onComplete: params.onComplete);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformPrintJobController}
class IOSPrintJobController extends PlatformPrintJobController
with ChannelController {
/// Constructs a [IOSPrintJobController].
IOSPrintJobController(PlatformPrintJobControllerCreationParams params)
: super.implementation(
params is IOSPrintJobControllerCreationParams
? params
: IOSPrintJobControllerCreationParams
.fromPlatformPrintJobControllerCreationParams(params),
) {
onComplete = params.onComplete;
channel = MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_printjobcontroller_${params.id}');
handler = _handleMethod;
initMethodCallHandler();
}
Future<dynamic> _handleMethod(MethodCall call) async {
switch (call.method) {
case "onComplete":
bool completed = call.arguments["completed"];
String? error = call.arguments["error"];
if (onComplete != null) {
onComplete!(completed, error);
}
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
}
@override
Future<void> dismiss({bool animated = true}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("animated", () => animated);
await channel?.invokeMethod('dismiss', args);
}
@override
Future<PrintJobInfo?> getInfo() async {
Map<String, dynamic> args = <String, dynamic>{};
Map<String, dynamic>? infoMap =
(await channel?.invokeMethod('getInfo', args))?.cast<String, dynamic>();
return PrintJobInfo.fromMap(infoMap);
}
@override
Future<void> dispose() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('dispose', args);
disposeChannel();
}
}
@@ -0,0 +1 @@
export 'pull_to_refresh_controller.dart' hide InternalPullToRefreshController;
@@ -0,0 +1,141 @@
import 'dart:ui';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
/// Object specifying creation parameters for creating a [IOSPullToRefreshController].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformPullToRefreshControllerCreationParams] for
/// more information.
class IOSPullToRefreshControllerCreationParams
extends PlatformPullToRefreshControllerCreationParams {
/// Creates a new [IOSPullToRefreshControllerCreationParams] instance.
IOSPullToRefreshControllerCreationParams(
{super.onRefresh, super.options, super.settings});
/// Creates a [IOSPullToRefreshControllerCreationParams] instance based on [PlatformPullToRefreshControllerCreationParams].
factory IOSPullToRefreshControllerCreationParams.fromPlatformPullToRefreshControllerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformPullToRefreshControllerCreationParams params) {
return IOSPullToRefreshControllerCreationParams(
onRefresh: params.onRefresh,
options: params.options,
settings: params.settings);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformPullToRefreshController}
class IOSPullToRefreshController extends PlatformPullToRefreshController
with ChannelController {
/// Constructs a [IOSPullToRefreshController].
IOSPullToRefreshController(
PlatformPullToRefreshControllerCreationParams params)
: super.implementation(
params is IOSPullToRefreshControllerCreationParams
? params
: IOSPullToRefreshControllerCreationParams
.fromPlatformPullToRefreshControllerCreationParams(params),
);
_debugLog(String method, dynamic args) {
debugLog(
className: this.runtimeType.toString(),
debugLoggingSettings:
PlatformPullToRefreshController.debugLoggingSettings,
method: method,
args: args);
}
Future<dynamic> _handleMethod(MethodCall call) async {
_debugLog(call.method, call.arguments);
switch (call.method) {
case "onRefresh":
if (params.onRefresh != null) params.onRefresh!();
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
return null;
}
@override
Future<void> setEnabled(bool enabled) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('enabled', () => enabled);
await channel?.invokeMethod('setEnabled', args);
}
@override
Future<bool> isEnabled() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('isEnabled', args) ?? false;
}
Future<void> _setRefreshing(bool refreshing) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('refreshing', () => refreshing);
await channel?.invokeMethod('setRefreshing', args);
}
@override
Future<void> beginRefreshing() async {
return await _setRefreshing(true);
}
@override
Future<void> endRefreshing() async {
await _setRefreshing(false);
}
@override
Future<bool> isRefreshing() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('isRefreshing', args) ?? false;
}
@override
Future<void> setColor(Color color) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('color', () => color.toHex());
await channel?.invokeMethod('setColor', args);
}
@override
Future<void> setBackgroundColor(Color color) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('color', () => color.toHex());
await channel?.invokeMethod('setBackgroundColor', args);
}
@Deprecated("Use setStyledTitle instead")
@override
Future<void> setAttributedTitle(IOSNSAttributedString attributedTitle) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('attributedTitle', () => attributedTitle.toMap());
await channel?.invokeMethod('setStyledTitle', args);
}
@override
Future<void> setStyledTitle(AttributedString attributedTitle) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('attributedTitle', () => attributedTitle.toMap());
await channel?.invokeMethod('setStyledTitle', args);
}
@override
void dispose({bool isKeepAlive = false}) {
disposeChannel(removeMethodCallHandler: !isKeepAlive);
}
}
extension InternalPullToRefreshController on IOSPullToRefreshController {
void init(dynamic id) {
channel = MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_pull_to_refresh_$id');
handler = _handleMethod;
initMethodCallHandler();
}
}
@@ -0,0 +1 @@
export 'web_authenticate_session.dart';
@@ -0,0 +1,163 @@
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
/// Object specifying creation parameters for creating a [IOSWebAuthenticationSession].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebAuthenticationSessionCreationParams] for
/// more information.
class IOSWebAuthenticationSessionCreationParams
extends PlatformWebAuthenticationSessionCreationParams {
/// Creates a new [IOSWebAuthenticationSessionCreationParams] instance.
const IOSWebAuthenticationSessionCreationParams();
/// Creates a [IOSWebAuthenticationSessionCreationParams] instance based on [PlatformWebAuthenticationSessionCreationParams].
factory IOSWebAuthenticationSessionCreationParams.fromPlatformWebAuthenticationSessionCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebAuthenticationSessionCreationParams params) {
return IOSWebAuthenticationSessionCreationParams();
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformWebAuthenticationSession}
class IOSWebAuthenticationSession extends PlatformWebAuthenticationSession
with ChannelController {
/// Constructs a [IOSWebAuthenticationSession].
IOSWebAuthenticationSession(
PlatformWebAuthenticationSessionCreationParams params)
: super.implementation(
params is IOSWebAuthenticationSessionCreationParams
? params
: IOSWebAuthenticationSessionCreationParams
.fromPlatformWebAuthenticationSessionCreationParams(params),
);
static final IOSWebAuthenticationSession _staticValue =
IOSWebAuthenticationSession(IOSWebAuthenticationSessionCreationParams());
/// Provide static access.
factory IOSWebAuthenticationSession.static() {
return _staticValue;
}
@override
final String id = IdGenerator.generate();
@override
late final WebUri url;
@override
late final String? callbackURLScheme;
@override
late final WebAuthenticationSessionSettings? initialSettings;
@override
late final WebAuthenticationSessionCompletionHandler onComplete;
static const MethodChannel _staticChannel = const MethodChannel(
'com.pichillilorenzo/flutter_webauthenticationsession');
@override
Future<IOSWebAuthenticationSession> create(
{required WebUri url,
String? callbackURLScheme,
WebAuthenticationSessionCompletionHandler onComplete,
WebAuthenticationSessionSettings? initialSettings}) async {
var session = IOSWebAuthenticationSession._create(
url: url,
callbackURLScheme: callbackURLScheme,
onComplete: onComplete,
initialSettings: initialSettings);
initialSettings =
session.initialSettings ?? WebAuthenticationSessionSettings();
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("id", () => session.id);
args.putIfAbsent("url", () => session.url.toString());
args.putIfAbsent("callbackURLScheme", () => session.callbackURLScheme);
args.putIfAbsent("initialSettings", () => initialSettings?.toMap());
await _staticChannel.invokeMethod('create', args);
return session;
}
IOSWebAuthenticationSession._create(
{required this.url,
this.callbackURLScheme,
this.onComplete,
WebAuthenticationSessionSettings? initialSettings})
: super.implementation(IOSWebAuthenticationSessionCreationParams()) {
assert(url.toString().isNotEmpty);
assert(['http', 'https'].contains(url.scheme),
'The specified URL has an unsupported scheme. Only HTTP and HTTPS URLs are supported on iOS.');
this.initialSettings =
initialSettings ?? WebAuthenticationSessionSettings();
channel = MethodChannel(
'com.pichillilorenzo/flutter_webauthenticationsession_$id');
handler = _handleMethod;
initMethodCallHandler();
}
_debugLog(String method, dynamic args) {
debugLog(
className: this.runtimeType.toString(),
debugLoggingSettings:
PlatformWebAuthenticationSession.debugLoggingSettings,
id: id,
method: method,
args: args);
}
Future<dynamic> _handleMethod(MethodCall call) async {
_debugLog(call.method, call.arguments);
switch (call.method) {
case "onComplete":
String? url = call.arguments["url"];
WebUri? uri = url != null ? WebUri(url) : null;
var error = WebAuthenticationSessionError.fromNativeValue(
call.arguments["errorCode"]);
if (onComplete != null) {
onComplete!(uri, error);
}
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
}
@override
Future<bool> canStart() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('canStart', args) ?? false;
}
@override
Future<bool> start() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('start', args) ?? false;
}
@override
Future<void> cancel() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod("cancel", args);
}
@override
Future<void> dispose() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod("dispose", args);
disposeChannel();
}
@override
Future<bool> isAvailable() async {
Map<String, dynamic> args = <String, dynamic>{};
return await _staticChannel.invokeMethod<bool>("isAvailable", args) ??
false;
}
}
@@ -0,0 +1,3 @@
export 'web_message_port.dart' hide InternalWebMessagePort;
export 'web_message_channel.dart' hide InternalWebMessageChannel;
export 'web_message_listener.dart';
@@ -0,0 +1,117 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'web_message_port.dart';
/// Object specifying creation parameters for creating a [IOSWebMessageChannel].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebMessageChannelCreationParams] for
/// more information.
@immutable
class IOSWebMessageChannelCreationParams
extends PlatformWebMessageChannelCreationParams {
/// Creates a new [IOSWebMessageChannelCreationParams] instance.
const IOSWebMessageChannelCreationParams(
{required super.id, required super.port1, required super.port2});
/// Creates a [IOSWebMessageChannelCreationParams] instance based on [PlatformWebMessageChannelCreationParams].
factory IOSWebMessageChannelCreationParams.fromPlatformWebMessageChannelCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebMessageChannelCreationParams params) {
return IOSWebMessageChannelCreationParams(
id: params.id, port1: params.port1, port2: params.port2);
}
@override
String toString() {
return 'IOSWebMessageChannelCreationParams{id: $id, port1: $port1, port2: $port2}';
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformWebMessageChannel}
class IOSWebMessageChannel extends PlatformWebMessageChannel
with ChannelController {
/// Constructs a [IOSWebMessageChannel].
IOSWebMessageChannel(PlatformWebMessageChannelCreationParams params)
: super.implementation(
params is IOSWebMessageChannelCreationParams
? params
: IOSWebMessageChannelCreationParams
.fromPlatformWebMessageChannelCreationParams(params),
) {
channel = MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_web_message_channel_${params.id}');
handler = _handleMethod;
initMethodCallHandler();
}
static final IOSWebMessageChannel _staticValue = IOSWebMessageChannel(
IOSWebMessageChannelCreationParams(
id: '',
port1: IOSWebMessagePort(IOSWebMessagePortCreationParams(index: 0)),
port2: IOSWebMessagePort(IOSWebMessagePortCreationParams(index: 1))));
/// Provide static access.
factory IOSWebMessageChannel.static() {
return _staticValue;
}
IOSWebMessagePort get _iosPort1 => port1 as IOSWebMessagePort;
IOSWebMessagePort get _iosPort2 => port2 as IOSWebMessagePort;
static IOSWebMessageChannel? _fromMap(Map<String, dynamic>? map) {
if (map == null) {
return null;
}
var webMessageChannel = IOSWebMessageChannel(
IOSWebMessageChannelCreationParams(
id: map["id"],
port1: IOSWebMessagePort(IOSWebMessagePortCreationParams(index: 0)),
port2:
IOSWebMessagePort(IOSWebMessagePortCreationParams(index: 1))));
webMessageChannel._iosPort1.webMessageChannel = webMessageChannel;
webMessageChannel._iosPort2.webMessageChannel = webMessageChannel;
return webMessageChannel;
}
Future<dynamic> _handleMethod(MethodCall call) async {
switch (call.method) {
case "onMessage":
int index = call.arguments["index"];
var port = index == 0 ? _iosPort1 : _iosPort2;
if (port.onMessage != null) {
WebMessage? message = call.arguments["message"] != null
? WebMessage.fromMap(
call.arguments["message"].cast<String, dynamic>())
: null;
port.onMessage!(message);
}
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
return null;
}
@override
IOSWebMessageChannel? fromMap(Map<String, dynamic>? map) {
return _fromMap(map);
}
@override
void dispose() {
disposeChannel();
}
@override
String toString() {
return 'IOSWebMessageChannel{id: $id, port1: $port1, port2: $port2}';
}
}
extension InternalWebMessageChannel on IOSWebMessageChannel {
MethodChannel? get internalChannel => channel;
}
@@ -0,0 +1,164 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
/// Object specifying creation parameters for creating a [IOSWebMessageListener].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebMessageListenerCreationParams] for
/// more information.
@immutable
class IOSWebMessageListenerCreationParams
extends PlatformWebMessageListenerCreationParams {
/// Creates a new [IOSWebMessageListenerCreationParams] instance.
const IOSWebMessageListenerCreationParams(
{required this.allowedOriginRules,
required super.jsObjectName,
super.onPostMessage});
/// Creates a [IOSWebMessageListenerCreationParams] instance based on [PlatformWebMessageListenerCreationParams].
factory IOSWebMessageListenerCreationParams.fromPlatformWebMessageListenerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebMessageListenerCreationParams params) {
return IOSWebMessageListenerCreationParams(
allowedOriginRules: params.allowedOriginRules ?? Set.from(["*"]),
jsObjectName: params.jsObjectName,
onPostMessage: params.onPostMessage);
}
@override
final Set<String> allowedOriginRules;
@override
String toString() {
return 'IOSWebMessageListenerCreationParams{jsObjectName: $jsObjectName, allowedOriginRules: $allowedOriginRules, onPostMessage: $onPostMessage}';
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformWebMessageListener}
class IOSWebMessageListener extends PlatformWebMessageListener
with ChannelController {
/// Constructs a [IOSWebMessageListener].
IOSWebMessageListener(PlatformWebMessageListenerCreationParams params)
: super.implementation(
params is IOSWebMessageListenerCreationParams
? params
: IOSWebMessageListenerCreationParams
.fromPlatformWebMessageListenerCreationParams(params),
) {
assert(!this._iosParams.allowedOriginRules.contains(""),
"allowedOriginRules cannot contain empty strings");
channel = MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_web_message_listener_${_id}_${params.jsObjectName}');
handler = _handleMethod;
initMethodCallHandler();
}
///Message Listener ID used internally.
final String _id = IdGenerator.generate();
IOSJavaScriptReplyProxy? _replyProxy;
IOSWebMessageListenerCreationParams get _iosParams =>
params as IOSWebMessageListenerCreationParams;
Future<dynamic> _handleMethod(MethodCall call) async {
switch (call.method) {
case "onPostMessage":
if (_replyProxy == null) {
_replyProxy = IOSJavaScriptReplyProxy(
PlatformJavaScriptReplyProxyCreationParams(
webMessageListener: this));
}
if (onPostMessage != null) {
WebMessage? message = call.arguments["message"] != null
? WebMessage.fromMap(
call.arguments["message"].cast<String, dynamic>())
: null;
WebUri? sourceOrigin = call.arguments["sourceOrigin"] != null
? WebUri(call.arguments["sourceOrigin"])
: null;
bool isMainFrame = call.arguments["isMainFrame"];
onPostMessage!(message, sourceOrigin, isMainFrame, _replyProxy!);
}
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
return null;
}
@override
void dispose() {
disposeChannel();
}
@override
Map<String, dynamic> toMap() {
return {
"id": _id,
"jsObjectName": params.jsObjectName,
"allowedOriginRules": _iosParams.allowedOriginRules.toList(),
};
}
@override
Map<String, dynamic> toJson() {
return this.toMap();
}
@override
String toString() {
return 'IOSWebMessageListener{id: ${_id}, jsObjectName: ${params.jsObjectName}, allowedOriginRules: ${params.allowedOriginRules}, replyProxy: $_replyProxy}';
}
}
/// Object specifying creation parameters for creating a [IOSJavaScriptReplyProxy].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformJavaScriptReplyProxyCreationParams] for
/// more information.
@immutable
class IOSJavaScriptReplyProxyCreationParams
extends PlatformJavaScriptReplyProxyCreationParams {
/// Creates a new [IOSJavaScriptReplyProxyCreationParams] instance.
const IOSJavaScriptReplyProxyCreationParams(
{required super.webMessageListener});
/// Creates a [IOSJavaScriptReplyProxyCreationParams] instance based on [PlatformJavaScriptReplyProxyCreationParams].
factory IOSJavaScriptReplyProxyCreationParams.fromPlatformJavaScriptReplyProxyCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformJavaScriptReplyProxyCreationParams params) {
return IOSJavaScriptReplyProxyCreationParams(
webMessageListener: params.webMessageListener);
}
}
///{@macro flutter_inappwebview_platform_interface.JavaScriptReplyProxy}
class IOSJavaScriptReplyProxy extends PlatformJavaScriptReplyProxy {
/// Constructs a [IOSWebMessageListener].
IOSJavaScriptReplyProxy(PlatformJavaScriptReplyProxyCreationParams params)
: super.implementation(
params is IOSJavaScriptReplyProxyCreationParams
? params
: IOSJavaScriptReplyProxyCreationParams
.fromPlatformJavaScriptReplyProxyCreationParams(params),
);
IOSWebMessageListener get _iosWebMessageListener =>
params.webMessageListener as IOSWebMessageListener;
@override
Future<void> postMessage(WebMessage message) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('message', () => message.toMap());
await _iosWebMessageListener.channel?.invokeMethod('postMessage', args);
}
@override
String toString() {
return 'IOSJavaScriptReplyProxy{}';
}
}
@@ -0,0 +1,95 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'web_message_channel.dart';
/// Object specifying creation parameters for creating a [IOSWebMessagePort].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebMessagePortCreationParams] for
/// more information.
@immutable
class IOSWebMessagePortCreationParams
extends PlatformWebMessagePortCreationParams {
/// Creates a new [IOSWebMessagePortCreationParams] instance.
const IOSWebMessagePortCreationParams({required super.index});
/// Creates a [IOSWebMessagePortCreationParams] instance based on [PlatformWebMessagePortCreationParams].
factory IOSWebMessagePortCreationParams.fromPlatformWebMessagePortCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebMessagePortCreationParams params) {
return IOSWebMessagePortCreationParams(index: params.index);
}
@override
String toString() {
return 'IOSWebMessagePortCreationParams{index: $index}';
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformWebMessagePort}
class IOSWebMessagePort extends PlatformWebMessagePort {
WebMessageCallback? _onMessage;
late IOSWebMessageChannel _webMessageChannel;
/// Constructs a [IOSWebMessagePort].
IOSWebMessagePort(PlatformWebMessagePortCreationParams params)
: super.implementation(
params is IOSWebMessagePortCreationParams
? params
: IOSWebMessagePortCreationParams
.fromPlatformWebMessagePortCreationParams(params),
);
@override
Future<void> setWebMessageCallback(WebMessageCallback? onMessage) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('index', () => params.index);
await _webMessageChannel.internalChannel
?.invokeMethod('setWebMessageCallback', args);
this._onMessage = onMessage;
}
@override
Future<void> postMessage(WebMessage message) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('index', () => params.index);
args.putIfAbsent('message', () => message.toMap());
await _webMessageChannel.internalChannel?.invokeMethod('postMessage', args);
}
@override
Future<void> close() async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('index', () => params.index);
await _webMessageChannel.internalChannel?.invokeMethod('close', args);
}
@override
Map<String, dynamic> toMap() {
return {
"index": params.index,
"webMessageChannelId": this._webMessageChannel.params.id
};
}
@override
Map<String, dynamic> toJson() {
return toMap();
}
@override
String toString() {
return 'IOSWebMessagePort{index: ${params.index}}';
}
}
extension InternalWebMessagePort on IOSWebMessagePort {
WebMessageCallback? get onMessage => _onMessage;
void set onMessage(WebMessageCallback? value) => _onMessage = value;
IOSWebMessageChannel get webMessageChannel => _webMessageChannel;
void set webMessageChannel(IOSWebMessageChannel value) =>
_webMessageChannel = value;
}
@@ -0,0 +1,2 @@
export 'web_storage.dart';
export 'web_storage_manager.dart' hide InternalWebStorageManager;
@@ -0,0 +1,256 @@
import 'dart:convert';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import '../in_app_webview/in_app_webview_controller.dart';
/// Object specifying creation parameters for creating a [IOSWebStorage].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebStorageCreationParams] for
/// more information.
class IOSWebStorageCreationParams extends PlatformWebStorageCreationParams {
/// Creates a new [IOSWebStorageCreationParams] instance.
IOSWebStorageCreationParams(
{required super.localStorage, required super.sessionStorage});
/// Creates a [IOSWebStorageCreationParams] instance based on [PlatformWebStorageCreationParams].
factory IOSWebStorageCreationParams.fromPlatformWebStorageCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebStorageCreationParams params) {
return IOSWebStorageCreationParams(
localStorage: params.localStorage,
sessionStorage: params.sessionStorage);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformWebStorage}
class IOSWebStorage extends PlatformWebStorage {
/// Constructs a [IOSWebStorage].
IOSWebStorage(PlatformWebStorageCreationParams params)
: super.implementation(
params is IOSWebStorageCreationParams
? params
: IOSWebStorageCreationParams
.fromPlatformWebStorageCreationParams(params),
);
@override
PlatformLocalStorage get localStorage => params.localStorage;
@override
PlatformSessionStorage get sessionStorage => params.sessionStorage;
@override
void dispose() {
localStorage.dispose();
sessionStorage.dispose();
}
}
/// Object specifying creation parameters for creating a [IOSStorage].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformStorageCreationParams] for
/// more information.
class IOSStorageCreationParams extends PlatformStorageCreationParams {
/// Creates a new [IOSStorageCreationParams] instance.
IOSStorageCreationParams(
{required super.controller, required super.webStorageType});
/// Creates a [IOSStorageCreationParams] instance based on [PlatformStorageCreationParams].
factory IOSStorageCreationParams.fromPlatformStorageCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformStorageCreationParams params) {
return IOSStorageCreationParams(
controller: params.controller, webStorageType: params.webStorageType);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformStorage}
abstract mixin class IOSStorage implements PlatformStorage {
@override
IOSInAppWebViewController? controller;
@override
Future<int?> length() async {
var result = await controller?.evaluateJavascript(source: """
window.$webStorageType.length;
""");
return result != null ? int.parse(json.decode(result)) : null;
}
@override
Future<void> setItem({required String key, required dynamic value}) async {
var encodedValue = json.encode(value);
await controller?.evaluateJavascript(source: """
window.$webStorageType.setItem("$key", ${value is String ? encodedValue : "JSON.stringify($encodedValue)"});
""");
}
@override
Future<dynamic> getItem({required String key}) async {
var itemValue = await controller?.evaluateJavascript(source: """
window.$webStorageType.getItem("$key");
""");
if (itemValue == null) {
return null;
}
try {
return json.decode(itemValue);
} catch (e) {}
return itemValue;
}
@override
Future<void> removeItem({required String key}) async {
await controller?.evaluateJavascript(source: """
window.$webStorageType.removeItem("$key");
""");
}
@override
Future<List<WebStorageItem>> getItems() async {
var webStorageItems = <WebStorageItem>[];
List<Map<dynamic, dynamic>>? items =
(await controller?.evaluateJavascript(source: """
(function() {
var webStorageItems = [];
for(var i = 0; i < window.$webStorageType.length; i++){
var key = window.$webStorageType.key(i);
webStorageItems.push(
{
key: key,
value: window.$webStorageType.getItem(key)
}
);
}
return webStorageItems;
})();
"""))?.cast<Map<dynamic, dynamic>>();
if (items == null) {
return webStorageItems;
}
for (var item in items) {
webStorageItems
.add(WebStorageItem(key: item["key"], value: item["value"]));
}
return webStorageItems;
}
@override
Future<void> clear() async {
await controller?.evaluateJavascript(source: """
window.$webStorageType.clear();
""");
}
@override
Future<String> key({required int index}) async {
var result = await controller?.evaluateJavascript(source: """
window.$webStorageType.key($index);
""");
return result != null ? json.decode(result) : null;
}
@override
void dispose() {
controller = null;
}
}
/// Object specifying creation parameters for creating a [IOSLocalStorage].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformLocalStorageCreationParams] for
/// more information.
class IOSLocalStorageCreationParams extends PlatformLocalStorageCreationParams {
/// Creates a new [IOSLocalStorageCreationParams] instance.
IOSLocalStorageCreationParams(super.params);
/// Creates a [IOSLocalStorageCreationParams] instance based on [PlatformLocalStorageCreationParams].
factory IOSLocalStorageCreationParams.fromPlatformLocalStorageCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformLocalStorageCreationParams params) {
return IOSLocalStorageCreationParams(params);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformLocalStorage}
class IOSLocalStorage extends PlatformLocalStorage with IOSStorage {
/// Constructs a [IOSLocalStorage].
IOSLocalStorage(PlatformLocalStorageCreationParams params)
: super.implementation(
params is IOSLocalStorageCreationParams
? params
: IOSLocalStorageCreationParams
.fromPlatformLocalStorageCreationParams(params),
);
/// Default storage
factory IOSLocalStorage.defaultStorage(
{required PlatformInAppWebViewController? controller}) {
return IOSLocalStorage(IOSLocalStorageCreationParams(
PlatformLocalStorageCreationParams(PlatformStorageCreationParams(
controller: controller,
webStorageType: WebStorageType.LOCAL_STORAGE))));
}
@override
IOSInAppWebViewController? get controller =>
params.controller as IOSInAppWebViewController?;
}
/// Object specifying creation parameters for creating a [IOSSessionStorage].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformSessionStorageCreationParams] for
/// more information.
class IOSSessionStorageCreationParams
extends PlatformSessionStorageCreationParams {
/// Creates a new [IOSSessionStorageCreationParams] instance.
IOSSessionStorageCreationParams(super.params);
/// Creates a [IOSSessionStorageCreationParams] instance based on [PlatformSessionStorageCreationParams].
factory IOSSessionStorageCreationParams.fromPlatformSessionStorageCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformSessionStorageCreationParams params) {
return IOSSessionStorageCreationParams(params);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformSessionStorage}
class IOSSessionStorage extends PlatformSessionStorage with IOSStorage {
/// Constructs a [IOSSessionStorage].
IOSSessionStorage(PlatformSessionStorageCreationParams params)
: super.implementation(
params is IOSSessionStorageCreationParams
? params
: IOSSessionStorageCreationParams
.fromPlatformSessionStorageCreationParams(params),
);
/// Default storage
factory IOSSessionStorage.defaultStorage(
{required PlatformInAppWebViewController? controller}) {
return IOSSessionStorage(IOSSessionStorageCreationParams(
PlatformSessionStorageCreationParams(PlatformStorageCreationParams(
controller: controller,
webStorageType: WebStorageType.SESSION_STORAGE))));
}
@override
IOSInAppWebViewController? get controller =>
params.controller as IOSInAppWebViewController?;
}
@@ -0,0 +1,134 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
/// Object specifying creation parameters for creating a [IOSWebStorageManager].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebStorageManagerCreationParams] for
/// more information.
@immutable
class IOSWebStorageManagerCreationParams
extends PlatformWebStorageManagerCreationParams {
/// Creates a new [IOSWebStorageManagerCreationParams] instance.
const IOSWebStorageManagerCreationParams(
// This parameter prevents breaking changes later.
// ignore: avoid_unused_constructor_parameters
PlatformWebStorageManagerCreationParams params,
) : super();
/// Creates a [IOSWebStorageManagerCreationParams] instance based on [PlatformWebStorageManagerCreationParams].
factory IOSWebStorageManagerCreationParams.fromPlatformWebStorageManagerCreationParams(
PlatformWebStorageManagerCreationParams params) {
return IOSWebStorageManagerCreationParams(params);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformWebStorageManager}
class IOSWebStorageManager extends PlatformWebStorageManager
with ChannelController {
/// Creates a new [IOSWebStorageManager].
IOSWebStorageManager(PlatformWebStorageManagerCreationParams params)
: super.implementation(
params is IOSWebStorageManagerCreationParams
? params
: IOSWebStorageManagerCreationParams
.fromPlatformWebStorageManagerCreationParams(params),
) {
channel = const MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_webstoragemanager');
handler = handleMethod;
initMethodCallHandler();
}
static IOSWebStorageManager? _instance;
///Gets the WebStorage manager shared instance.
static IOSWebStorageManager instance() {
return (_instance != null) ? _instance! : _init();
}
static IOSWebStorageManager _init() {
_instance = IOSWebStorageManager(IOSWebStorageManagerCreationParams(
const PlatformWebStorageManagerCreationParams()));
return _instance!;
}
Future<dynamic> _handleMethod(MethodCall call) async {}
@override
Future<List<WebsiteDataRecord>> fetchDataRecords(
{required Set<WebsiteDataType> dataTypes}) async {
List<WebsiteDataRecord> recordList = [];
List<String> dataTypesList = [];
for (var dataType in dataTypes) {
dataTypesList.add(dataType.toNativeValue());
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("dataTypes", () => dataTypesList);
List<Map<dynamic, dynamic>> records =
(await channel?.invokeMethod<List>('fetchDataRecords', args))
?.cast<Map<dynamic, dynamic>>() ??
[];
for (var record in records) {
List<String> dataTypesString = record["dataTypes"].cast<String>();
Set<WebsiteDataType> dataTypes = Set();
for (var dataTypeValue in dataTypesString) {
var dataType = WebsiteDataType.fromNativeValue(dataTypeValue);
if (dataType != null) {
dataTypes.add(dataType);
}
}
recordList.add(WebsiteDataRecord(
displayName: record["displayName"], dataTypes: dataTypes));
}
return recordList;
}
@override
Future<void> removeDataFor(
{required Set<WebsiteDataType> dataTypes,
required List<WebsiteDataRecord> dataRecords}) async {
List<String> dataTypesList = [];
for (var dataType in dataTypes) {
dataTypesList.add(dataType.toNativeValue());
}
List<Map<String, dynamic>> recordList = [];
for (var record in dataRecords) {
recordList.add(record.toMap());
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("dataTypes", () => dataTypesList);
args.putIfAbsent("recordList", () => recordList);
await channel?.invokeMethod('removeDataFor', args);
}
@override
Future<void> removeDataModifiedSince(
{required Set<WebsiteDataType> dataTypes, required DateTime date}) async {
List<String> dataTypesList = [];
for (var dataType in dataTypes) {
dataTypesList.add(dataType.toNativeValue());
}
var timestamp = date.millisecondsSinceEpoch;
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("dataTypes", () => dataTypesList);
args.putIfAbsent("timestamp", () => timestamp);
await channel?.invokeMethod('removeDataModifiedSince', args);
}
@override
void dispose() {
// empty
}
}
extension InternalWebStorageManager on IOSWebStorageManager {
get handleMethod => _handleMethod;
}