setCookie method
Sets a cookie for the given url
. Any existing cookie with the same host
, path
and name
will be replaced with the new cookie.
The cookie being set will be ignored if it is expired.
The default value of path
is "/"
.
iosBelow11WebViewController
could be used if you need to set a session-only cookie using JavaScript (so isHttpOnly
cannot be set, see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies)
on the current URL of the WebView managed by that controller when you need to target iOS below 11. In this case the url
parameter is ignored.
NOTE for iOS below 11.0: If iosBelow11WebViewController
is null
or JavaScript is disabled for it, it will try to use a HeadlessInAppWebView
to set the cookie (session-only cookie won't work! In that case, you should set also expiresDate
or maxAge
).
Implementation
Future<void> setCookie(
{required Uri url,
required String name,
required String value,
String path = "/",
String? domain,
int? expiresDate,
int? maxAge,
bool? isSecure,
bool? isHttpOnly,
HTTPCookieSameSitePolicy? sameSite,
InAppWebViewController? iosBelow11WebViewController}) async {
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: iosBelow11WebViewController);
return;
}
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?.toValue());
await _channel.invokeMethod('setCookie', args);
}