skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. You can do that with initialUrl & onPageFinished params

    String initialUrl = "https://flutter.dev/";
    String cookie = "session_id=12345";
    
    WebViewWidget(
      controller: widget.controller,
      initialUrl: '$initialUrl?cookie=$cookie',
      onPageFinished: (url) async {
        final cookies = await _webViewController.runJavaScriptReturningResult(
          'document.cookie',
        );
        print("cookie: $cookies");
      },
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search