getCookie method
- required Uri url,
- required String name,
- InAppWebViewController? iosBelow11WebViewController,
Gets a cookie by its name
for the given url
.
iosBelow11WebViewController
is used for getting the cookie (also session-only cookie) using JavaScript (cookie with isHttpOnly
enabled cannot be found, see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies)
from the current context of the WebView managed by that controller when you need to target iOS below 11. JavaScript must be enabled in order to work.
In this case the url
parameter is ignored.
NOTE for iOS below 11.0: All the cookies returned this way will have all the properties to null
except for Cookie.name and Cookie.value.
If iosBelow11WebViewController
is null
or JavaScript is disabled for it, it will try to use a HeadlessInAppWebView
to get the cookie (session-only cookie and cookie with isHttpOnly
enabled won't be found!).
Implementation
Future<Cookie?> getCookie(
{required Uri url,
required String name,
InAppWebViewController? iosBelow11WebViewController}) async {
assert(url.toString().isNotEmpty);
assert(name.isNotEmpty);
if (await _shouldUseJavascript()) {
List<Cookie> cookies = await _getCookiesWithJavaScript(
url: url, webViewController: iosBelow11WebViewController);
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('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.fromValue(cookies[i]["sameSite"]),
isSecure: cookies[i]["isSecure"],
isHttpOnly: cookies[i]["isHttpOnly"],
path: cookies[i]["path"]);
}
return null;
}