pichillilorenzo / flutter_inappwebview

A Flutter plugin that allows you to add an inline webview, to use a headless webview, and to open an in-app browser window.
https://inappwebview.dev
Apache License 2.0
3.28k stars 1.62k forks source link

Adding cookie in InAppWebview problem since I cannot find full example code with cookie #894

Closed djks74 closed 1 month ago

djks74 commented 3 years ago

Environment

Technology Version
Flutter version 2.2.0
Plugin version 5.3.2

Device information:

Description

Expected behavior: When I open InAppWebview with url from my site, it should loading the page and read cookies as I needed when user logged in.

Current behavior: Cookie only working after I open flutter_webview from flutter webview plugin in other page, this cookie not working since I might wrong to embeed it? Please help me to fix my code working with cookie?

Steps to reproduce

import 'dart:async'; import 'dart:collection'; import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:webview_cookie_manager/webview_cookie_manager.dart'; import '../../resources/api_provider.dart';

Future main() async { WidgetsFlutterBinding.ensureInitialized();

if (Platform.isAndroid) { await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true); }

runApp(new MyApp()); }

class MyApp extends StatefulWidget { final String url; final String title; const MyApp({Key key, this.url, this.title}) : super(key: key); @override _MyAppState createState() => new _MyAppState(); }

class _MyAppState extends State { final GlobalKey webViewKey = GlobalKey();

InAppWebViewController webViewController; InAppWebViewGroupOptions options = InAppWebViewGroupOptions( crossPlatform: InAppWebViewOptions( useShouldOverrideUrlLoading: true, mediaPlaybackRequiresUserGesture: false, ), android: AndroidInAppWebViewOptions( useHybridComposition: true, ), ios: IOSInAppWebViewOptions( allowsInlineMediaPlayback: true, ));

PullToRefreshController pullToRefreshController; String url = ""; double progress = 0; final urlController = TextEditingController(); CookieManager _cookieManager = CookieManager.instance(); InAppWebViewController webView; final cookieManager = WebviewCookieManager(); bool injectCookies = false; final expiresDate = DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;

@override void initState() { _seCookies(); super.initState();

pullToRefreshController = PullToRefreshController(
  options: PullToRefreshOptions(
    color: Colors.blue,
  ),
  onRefresh: () async {
    if (Platform.isAndroid) {
      webViewController?.reload();
    } else if (Platform.isIOS) {
      webViewController?.loadUrl(
          urlRequest: URLRequest(url: await webViewController?.getUrl()));
    }
  },
);

}

@override void dispose() { super.dispose(); }

@override Widget build(BuildContext context) { return Scaffold( appBar: widget.title != null ? AppBar(title: Text(widget.title)) : AppBar(), body: Container( child: Stack( children: [ injectCookies ? InAppWebView( key: webViewKey, initialUrlRequest: URLRequest( url: Uri.parse( "https://mysite.co.id/store-manager/orderslist")), initialOptions: options, pullToRefreshController: pullToRefreshController, onWebViewCreated: (controller) { webViewController = controller; }, onLoadStart: (controller, url) { setState(() { this.url = url.toString(); urlController.text = this.url; }); }, androidOnPermissionRequest: (controller, origin, resources) async { return PermissionRequestResponse( resources: resources, action: PermissionRequestResponseAction.GRANT); }, shouldOverrideUrlLoading: (controller, navigationAction) async { var uri = navigationAction.request.url;

                  if (![
                    "http",
                    "https",
                    "file",
                    "chrome",
                    "data",
                    "javascript",
                    "about",
                  ].contains(uri.scheme)) {
                    if (await canLaunch(url)) {
                      // Launch the App
                      await launch(
                        url,
                      );
                      // and cancel the request
                      return NavigationActionPolicy.CANCEL;
                    }
                  }

                  return NavigationActionPolicy.ALLOW;
                },
                onLoadStop: (controller, url) async {
                  List<Cookie> cookies =
                      await _cookieManager.getCookies(url: url);
                  cookies.forEach((cookie) {
                    print(cookie.name + " " + cookie.value);
                  });
                },
                onLoadError: (controller, url, code, message) {
                  pullToRefreshController.endRefreshing();
                },
                onProgressChanged: (controller, progress) {
                  if (progress == 100) {
                    pullToRefreshController.endRefreshing();
                  }
                  setState(() {
                    this.progress = progress / 100;
                    urlController.text = this.url;
                  });
                },
                onUpdateVisitedHistory: (controller, url, androidIsReload) {
                  setState(() {
                    this.url = url.toString();
                    urlController.text = this.url;
                  });
                },
                onConsoleMessage: (controller, consoleMessage) {
                  print(consoleMessage);
                },
              )
            : progress < 1.0
                ? LinearProgressIndicator(value: progress)
                : Container(),
      ],
    ),
  ),
);

}

_seCookies() async { Uri uri = Uri.parse(url); String domain = uri.host; print('Domain: ' + domain); ApiProvider apiProvider = ApiProvider();

apiProvider.cookieList.forEach((element) async {
  await cookieManager.setCookies([
    //..expires = DateTime.now().add(Duration(days: 10))
    //..httpOnly = true
  ]);
});
setState(() {
  injectCookies = true;
});

} }

============================== I cannot find any example with new version 5.3.2 for cookie embeeded.

Hope you can help me to fix the cookie for this code with InAppWebview.

With older InAppbrowser last time I can manage with webview cookie manager plugin, but with newest InAppwebview update now cookie is messed with webview cookie manager and I confuse to fix the code since I really not coder!

If you think without webview cookie manager is fine, hope you can help me to fix my code.

Please help! Thanks in advance.

with kind regards, Sandi

github-actions[bot] commented 3 years ago

👋 @djks74

NOTE: This comment is auto-generated.

Are you sure you have already searched for the same problem?

Some people open new issues but they didn't search for something similar or for the same issue. Please, search for it using the GitHub issue search box or on the official inappwebview.dev website, or, also, using Google, StackOverflow, etc. before posting a new one. You may already find an answer to your problem!

If this is really a new issue, then thank you for raising it. I will investigate it and get back to you as soon as possible. Please, make sure you have given me as much context as possible! Also, if you didn't already, post a code example that can replicate this issue.

In the meantime, you can already search for some possible solutions online! Because this plugin uses native WebView, you can search online for the same issue adding android WebView [MY ERROR HERE] or ios WKWebView [MY ERROR HERE] keywords.

Following these steps can save you, me, and other people a lot of time, thanks!

djks74 commented 3 years ago

Yes, I did searching and cannot find full code of example InAppWebview with cookie embeeded.

Please help! Thanks.

alectogeek commented 2 years ago

I can't find appropriate di=ocumentation as well. Neither about how does it work by default nor how to store and reuse cookies manually.

github-actions[bot] commented 1 month ago

This issue is stale and has been automatically closed because it has been open for more than 365 days with no activity. Please reopen a new issue if you still have it.

github-actions[bot] commented 1 week ago

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug and a minimal reproduction of the issue.