skip to Main Content

I have a webview on a Pageview who display a chat from a plugin that I use on my wordpress website (I have no access to data from this plugin). It’s not a chat with FB or google account, it’s only an open chat room, where users can add and save her nickname (I suppose nickname is stored in cookies ?). As long as the webview is active the nickname remains memorized. Problem, after each time the app is close and reopen, the user lose his nickname.

Here is my code

WebView(
        initialUrl: 'https://XXXX',

        javascriptMode: JavascriptMode.unrestricted,

        gestureRecognizers: [
          Factory(() => PlatformViewVerticalGestureRecognizer()),
        ].toSet(),
      ),

How can I save session ? Even when after app is close and reopen ?

2

Answers


  1. First, in your website project, add this javascript code which it will be accessible to the HTML pseodo input:

       var psuedoInput = document.querySelector('inputSelectorHere');
    _selector.addEventListener('change', function(event) {
        var message = psuedoInput.value;
    
        if (messageHandler) {
            messageHandler.postMessage(message);
        }
        });
    

    you can add it inside a <script></script> in the .html file or in a .js separate file.

    this basically will post a message with the pseudo input value to our app later.

    Don’t forget to change inputSelectorHere with your psuedo input selector.

    now in your flutter code, create a simple Stirng variable like this:

      String? cookie;
    

    then in the WebView widget:

        WebView(
                javascriptChannels: <JavascriptChannel>[
                  // javascript channel that saves the cookie
                  JavascriptChannel(
                    name: 'Cookie',
                    onMessageReceived: (JavascriptMessage message) {
                      cookie = message.message;
                      print("cookie: $cookie");
                    },
                  ),
                ].toSet(),
                onWebViewCreated: (controller) {
                  if (cookie == null) {
                    return;
                  }
                controller.runJavascript("document.cookie = '$cookie';");
    
                  // }
                },
                initialCookies: [],
                initialUrl: 'https://XXXX',
                javascriptMode: JavascriptMode.unrestricted,
              ),
    

    here the JavascriptChannel is set so it receives those messages which will be sent from your website from the webview, then it will be saved inside the cookie variable which we created.

    when you close the webview and open it again, the onWebViewCreated will be called, and the cookie now is not null, so it will assign the cookie we saved to document.cookie in the webview.

    Login or Signup to reply.
  2. As I can understand. You just need to get cookies (or cache and local storage) and store them in FlutterSecureStorage. when the user closes the app and re-opens just check if cookies are stored in FlutterSecureStorage or not.

    If Cookies are present just add the cookies and refresh the page. I have written a pseudo code for the demo purpose (Code might not work as you expected but it will give you a brief idea about my approach).

    I have added a code for the cookies. I also added code for the cache and local storage but you have to configure it according to your needs.

    Please read the comments.

    import 'package:flutter/material.dart';
    import 'package:flutter_secure_storage/flutter_secure_storage.dart';
    import 'package:webview_flutter/webview_flutter.dart';
    
    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
    
      runApp(const FlutterWebViewDemo());
    }
    
    class FlutterWebViewDemo extends StatefulWidget {
      const FlutterWebViewDemo({Key? key}) : super(key: key);
    
      @override
      State<FlutterWebViewDemo> createState() => _FlutterWebViewDemoState();
    }
    
    class _FlutterWebViewDemoState extends State<FlutterWebViewDemo> {
      late final WebViewCookieManager cookieManager = WebViewCookieManager();
    
      var controller = WebViewController()
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..setBackgroundColor(const Color(0x00000000))
        ..setNavigationDelegate(
          NavigationDelegate(
            onProgress: (int progress) {
              // Update loading bar.
            },
            onPageStarted: (String url) {},
            onPageFinished: (String url) {},
            onWebResourceError: (WebResourceError error) {},
          ),
        )
        ..loadRequest(Uri.parse(''));
    
      /// <---- please add the url here
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Column(
              children: [
                Expanded(child: WebViewWidget(controller: controller)),
                ElevatedButton(
                  onPressed: () async {
                    _onListCache();
                  },
                  child: const Text("Save Cache"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    _onAddToCache();
                  },
                  child: const Text("Set Cache"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    _onClearCache();
                  },
                  child: const Text("Clear Cache"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    _onListCookies();
                  },
                  child: const Text("Save Cookies"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    _onSetCookie();
                  },
                  child: const Text("Set Cookies"),
                ),
                ElevatedButton(
                  onPressed: () async {
                    _onClearCookies();
                  },
                  child: const Text("Clear Cookies"),
                )
              ],
            ),
          ),
        );
      }
    
      Future<void> _onListCookies() async {
        final String cookies = await controller
            .runJavaScriptReturningResult('document.cookie') as String;
        FlutterSecureStorage secureStorage = const FlutterSecureStorage();
        secureStorage.write(key: 'cookies', value: cookies);
      }
    
      Future<void> _onSetCookie() async {
        FlutterSecureStorage secureStorage = const FlutterSecureStorage();
        String? cookies = await secureStorage.read(key: 'cookies');
    
        /// get cookies from flutter secure storage and set them and refresh the page with new cookies.
        /// please fill the required fields.
        await cookieManager.setCookie(
          WebViewCookie(
            name: '',
    
            /// required you have to set this
            value: cookies!,
            domain: '',
    
            /// required
            path: '/',
    
            /// required
          ),
        );
    
        /// this will load the new page
        await controller.loadRequest(Uri.parse(
          '',
    
          /// <---- refresh url
        ));
      }
    
      Future<void> _onClearCookies() async {
        final bool hadCookies = await cookieManager.clearCookies();
        String message = 'There were cookies. Now, they are gone!';
        if (!hadCookies) {
          message = 'There are no cookies.';
        }
        print(">>>>>>>>>> message $message");
      }
    
      Future<void> _onAddToCache() async {
        /// <--- you have to write the logic to add cache and local storage from flutter secure storage. like this and refresh the page.
        await controller.runJavaScript(
          'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";',
        );
      }
    
      Future _onListCache() async {
        await controller.runJavaScriptReturningResult('caches.keys()');
    
        /// <--- get cache and local storage and save it in flutter secure storage.
      }
    
      Future<void> _onClearCache() async {
        await controller.clearCache();
        await controller.clearLocalStorage();
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search