Search code examples
flutterdartcookiesflutter-inappwebview

Webview constantly refreshing - Flutter InAppWebView


So i'm trying to set a cookie (that sets the user token) in the Webview but I have this problem that the page keeps refreshing. here's the code :

InAppWebViewController _webViewController;
  final expiresDate = DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DashboardPageTitlesAtom(
        title: widget.title,
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        trailing: IconButton(
          icon: Icon(CupertinoIcons.refresh),
          onPressed: _webViewController == null ? null : () => _webViewController.reload(),
        ),
      ),
   
      body: Column(
        children: [
          Divider(
            thickness: 1,
            height: 1,
          ),
          Expanded(
            child: InAppWebView(
                initialOptions: InAppWebViewGroupOptions(
                  crossPlatform: InAppWebViewOptions(
                    javaScriptEnabled: true,
                    clearCache: false,
                  ),
                ),
                onWebViewCreated: (InAppWebViewController controller) async {
                  _webViewController = controller;
                },
                onLoadStop: (InAppWebViewController controller, url) async {
                  try {
                    final token = await getToken();
                    await _webViewController.evaluateJavascript(
                      source:
                          'document.cookie = "accessToken=${token}"; secure=true; httpOnly=false; sameSite=None',
                    );
                    await _webViewController.loadUrl(url: widget.url);
                  } catch (e) {
                    print(e.toString());
                  }
                }),
          ),
        ],
      ),
    );
  }

The problem is the only way to set the cookie is to refresh the page after evaluating the javascript and the page refresh doesn't stop. Thank you.


Solution

  • You are calling the loadUrl method inside the onLoadStop event. This way you are creating a loop cycle:

    "onLoadStop" -> "loadUrl" -> "onLoadStop" -> "loadUrl" -> "onLoadStop" -> etc.
    

    When onLoadStop gets called, you are loading the URL, so onLoadStop will get called again for that new URL request.

    To achieve what you need, you should use the CookieManager class and set the cookie when the WebView is created (that is in the onWebViewCreated event). Then, you call the loadUrl method with your URL request.

    In your scenario, you would have:

    onWebViewCreated: (controller) async {
      _webViewController = controller;
      try {
        // get the access token
        final token = await getToken();
    
        // get the CookieManager instance
        CookieManager cookieManager = CookieManager.instance();
    
        // set the access token
        await cookieManager.setCookie(
          url: widget.url,
          name: "accessToken",
          value: token,
          isSecure: true,
          isHttpOnly: false,
          sameSite: HTTPCookieSameSitePolicy.NONE
        );
    
        // then load your initial URL here
        await _webViewController.loadUrl(url: widget.url);
      } catch (e) {
        print(e.toString());
      }
    },