6

Using the webview_flutter package i could load my website and add session cookies to the initial URL.

_controller.future.then((controller) {
  _webViewController = controller;
  Map<String, String> header = {'Cookie': 'ci_session=${widget.sessionId}'};
  _webViewController.loadUrl('https://xxxx.com', headers: header);
});

In order to keep the session going i need to add the same header for all requests not just for the initial one. Is there any way to intercept all requests and modify them by adding headers to them?

the closest thing i found was navigationDelegate but it only returns a NavigationDecision which isn't useful in my case.

1
  • Have u found a solution for webview_flutter package May 22, 2021 at 11:38

2 Answers 2

13

You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

If you need to add custom headers for each request, you can use the shouldOverrideUrlLoading event (you need to enable it using useShouldOverrideUrlLoading: true option).

Instead, if you need to add cookies to your WebView, you can just use the CookieManager class (CookieManager.setCookie method to set a cookie).

Here is an example that set a cookie (named ci_session) in your WebView and also set a custom header (named My-Custom-Header) for each request:

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  CookieManager _cookieManager = CookieManager.instance();

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

    _cookieManager.setCookie(
      url: "https://github.com/",
      name: "ci_session",
      value: "54th5hfdcfg34",
      domain: ".github.com",
      isSecure: true,
    );
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "https://github.com/",
            initialHeaders: {'My-Custom-Header': 'custom_value=564hgf34'},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
                useShouldOverrideUrlLoading: true
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {},
            onLoadStop: (InAppWebViewController controller, String url) async {
              List<Cookie> cookies = await _cookieManager.getCookies(url: url);
              cookies.forEach((cookie) {
                print(cookie.name + " " + cookie.value);
              });
            },
            shouldOverrideUrlLoading: (controller, shouldOverrideUrlLoadingRequest) async {
              print("URL: ${shouldOverrideUrlLoadingRequest.url}");

              if (Platform.isAndroid || shouldOverrideUrlLoadingRequest.iosWKNavigationType == IOSWKNavigationType.LINK_ACTIVATED) {
                controller.loadUrl(url: shouldOverrideUrlLoadingRequest.url, headers: {
                  'My-Custom-Header': 'custom_value=564hgf34'
                });
                return ShouldOverrideUrlLoadingAction.CANCEL;
              }
              return ShouldOverrideUrlLoadingAction.ALLOW;
            },
          ))
        ])),
      ),
    );
  }
}
3
  • I ended up using it despite having some other problems. Gonna mark it as right answer anyway.
    – ibrahim
    Jun 2, 2020 at 16:53
  • For any other errors/problems related to the plugin, you can post them in the issue section Jun 2, 2020 at 16:59
  • does this work on iOS?
    – krjw
    Dec 15, 2022 at 15:00
2

in flutter_webview case

onWebViewCreated: (WebViewController webViewController) {
            this.webViewController = webViewController;
          },
onPageStarted: (url) {
            webViewController.loadUrl(url, headers: headers);
          },

use this

1
  • If a user clicks a button to load a new page i.e /login.html, could you add the header as well? Jun 20, 2022 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.