Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WebViewCookieManager.setCookie of webview_flutter

I'm quite new to Flutter. Currently I'm facing with problem of usage package webview_flutter from flutter docs at latest version (which is 4.0.7) for initial cookie when calling Webview in Flutter

WebView.initialCookies has been removed. Use WebViewCookieManager.setCookie before calling WebViewController.loadRequest.

Currently Flutter has change method WebView with controller into WebViewWidget with controller.

This is my new code for initialize WebView

_webViewController = WebViewController()
  ..loadRequest(
    Uri.parse("https://flutter.dev/"),
  )
  ..setJavaScriptMode(JavaScriptMode.unrestricted)
  ..setNavigationDelegate(NavigationDelegate(
    onPageStarted: (url) {
      print("come here: $url");
    },
    onPageFinished: (url) async {
      final cookies = await _webViewController.runJavaScriptReturningResult(
        'document.cookie',
      );
      // I can get cookie when page is reload or go to next page here
      print("cookie: $cookies");
    },
  ));

This is for build view

// view build
return Stack(
  children: [
    WebViewWidget(
      controller: widget.controller,
    ),
  ],
);

I can get website cookie everytime it reloads or go to next page by catch action onPageFinished. But the problem is I want to initalize URL with initialCookies when taping into Webview.

The answer currently is for webview_flutter: ^3.0.0 so it currently can't be use for latest version.

Thank you a lot for your help.

like image 700
Thang Phi Avatar asked Sep 16 '25 21:09

Thang Phi


1 Answers

For those who looking for an answer with version 4.0.0+ just like me.

This is my answer

WebViewCookie cookie =
    WebViewCookie(name: "sessionId", value: "12345678", domain: widget.url);
// Flutter has change to this
WebViewCookieManager().setCookie(cookie);
_webViewController = WebViewController()
  ..loadRequest(
    Uri.parse(widget.url),
  );

Note: Domain must be as same as the url when you call widget unless it will not call.

like image 148
Thang Phi Avatar answered Sep 19 '25 22:09

Thang Phi