How to set Cookies in webview_flutter?
Solution 1
Anyone still looking for an answer, the latest version of webview_flutter (webview_flutter: ^3.0.0
) includes the initialCookies
param which takes a list of WebViewCookie
.
eg.
sessionCookie = WebViewCookie(
name: 'my_session_cookie',
value: 'cookie_value',
domain: 'www.mydomain.com',
);
WebView(
initialCookies: [sessionCookie],
...
),
Solution 2
You can set cookie using Tow methods.
Solution 1.
Using webViewController.evaluateJavascript()
Eg:
final Completer<WebViewController> _controller =
Completer<WebViewController>();
WebViewController _webViewController;
@override
Widget build(BuildContext context) {
_controller.future.then((controller) {
_webViewController = controller;
_webViewController.loadUrl(URL);
});
return Scaffold(
body: SafeArea(
child: Container(
child:
WebView(
debuggingEnabled: true,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
onPageFinished: (String value) {
setSession(sessionId, _webViewController);
},
),
),
),
);
}
void setSession(String sessionId, WebViewController webViewController) async {
if (Platform.isIOS) {
await webViewController.evaluateJavascript("document.cookie = 'ASP.NET_SessionId=$sessionId'");
} else {
await webViewController.evaluateJavascript('document.cookie = "ASP.NET_SessionId=$sessionId; path=/"');
}
}
but using this we can set cookies after onPageFinished
in WebView. This solution will work only after you reload the webview. That means on the first build this method will add cookies to the WebView and will get result after second time onwards.
If you want WebView to load with preset Cookies check the next Solution
Solution 2. Using headers
we can set cookies while initiating an http request. Eg:
final Completer<WebViewController> _controller =
Completer<WebViewController>();
WebViewController _webViewController;
@override
Widget build(BuildContext context) {
_controller.future.then((controller) {
_webViewController = controller;
Map<String, String> header = {'Cookie': 'ASP.NET_SessionId=$sessionId'};
_webViewController.loadUrl(URL, headers: header);
});
return Scaffold(
body: SafeArea(
child: Container(
child:
WebView(
debuggingEnabled: true,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
),
),
),
);
}
This will load WebView with given Cookie.
Solution 3
With flutter 1.22.1
it works for me the following way:
WebView(
onWebViewCreated: (controller) {
controller.loadUrl(
"https://mypage.de/",
headers: {"Cookie": "mycookie=true"},
);
},
)
Notice that there is no colon in Cookie
as other answers suggested.
Update: Works with flutter 2 as well.
Solution 4
@deepakraj I have been trying to get one of those to work with no luck. The second one is the one I am most interested in. So Here is my code. I am simulating a leading async request to my backend which needs to resolve first in order to build the webview (source of the header) which is why I use a futureBuilder. Maybe I am having a glaring issue here.
WebViewController _webViewController;
Future ssoRequestFuture;
@override
void initState() {
// TODO: implement initState
super.initState();
this.ssoRequestFuture = makeGetRequest();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<http.Response>(
future: this.ssoRequestFuture,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Not connected');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('waiting');
case ConnectionState.done:
var cookieStr = snapshot.data.headers['set-cookie'];
List<String> cookies = cookieStr.split(","); // I am not interested n the first cookie
Cookie ssoCookie = Cookie.fromSetCookieValue(cookies[1]);
Map<String, String> header = {'Cookie': '$ssoCookie'};
// clear cookies was a suggestion ??
CookieManager cookieManager = CookieManager();
cookieManager.clearCookies();
return Scaffold(
body: Builder(builder: (BuildContext context) {
_controller.future.then((controller) {
_webViewController = controller;
_webViewController.loadUrl('http://192.168.86.28:4205', headers: header);
});
return WebView(
debuggingEnabled: true,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
gestureNavigationEnabled: true,
);
}),
);
default:
return Text('Default');
}
}
);
}
user12008123
Updated on December 13, 2022Comments
-
user12008123 over 1 year
How can I set Cookies in webview_flutter during initialization?
body: WebView initialUrl: index_url, javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (WebViewController webViewController) { _controller=webViewController; }, javascriptChannels: <JavascriptChannel>[ _toasterJavascriptChannel(context), ].toSet(), onPageFinished: (String url) { print('Page finished loading: $url'); }, ),
-
deepak raj about 4 yearsYou can clear cookies using CookieManager cookieManager = CookieManager(); bool hadCookies = await cookieManager.clearCookies();
-
TeeJaay about 4 yearsDid you ever try the second approach ? Looks like setting the cookie does not seem to work via the headers. github.com/flutter/flutter/issues/27597
-
deepak raj about 4 yearsAm using the second approach now to set cookie, and it is working fine. @TeeJaay Try to clear the cookie before setting new one.
-
Amit about 4 yearshi can u plz tell where to get $sessionId
-
deepak raj about 4 yearsSimply inspect the Webpage and select Application>Storage>Cookies there you can find Session_ID
-
rajeshzmoke almost 4 years@deepakraj can u post a sample code, 2nd approach does not seem to work
-
deepak raj almost 4 yearsI think the answer has required code. Just use the same.
-
Cyrus the Great over 3 yearsI used second way but nothing is happen stackoverflow.com/questions/65001831/… @deepakraj
-
deepak raj over 3 years@sayreskabir can you provide the URL you are testing.?
-
Cyrus the Great over 3 yearsipb.parsian-bank.ir/HDMap/… @deepakraj
-
deepak raj over 3 years@sayreskabir you can replace Map<String, String> header = {'Cookie': 'ASP.NET_SessionId=$sessionId'}; with Map<String, String> header = {'Cookie':'cookiesession1=$sessionId'};
-
Cyrus the Great over 3 yearsThis is my complete code : paste.ubuntu.com/p/htZk4YxcQs . in
onPageFinished
i try to print my cookieString cookies = await wvc.evaluateJavascript('document.cookie');
butString cookies
is empty?@deepakraj -
deepak raj over 3 years_webViewController.evaluateJavascript('document.cookie') will return an empty string because you are setting cookies in the header, not in the javascript.
-
Cyrus the Great over 3 yearsThen how can i get cookie from header?@deepakraj