Search code examples
androidflutterwebviewinterceptor

Flutter webview intercept and add headers to all requests


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.


Solution

  • 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;
                },
              ))
            ])),
          ),
        );
      }
    }