Flutter WebView拦截并向所有请求添加标头

时间:2020-04-28 13:57:13

标签: android flutter webview interceptor

使用webview_flutter软件包,我可以加载我的网站并将会话cookie添加到初始URL。

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

为了使会话继续进行,我需要为所有请求添加相同的标头,而不仅仅是最初的请求。 有什么方法可以拦截所有请求并通过向其添加标头来对其进行修改?

我找到的最接近的东西是navigationDelegate,但它只返回NavigationDecision,对我来说这没有用。

1 个答案:

答案 0 :(得分:4)

您可以使用我的插件flutter_inappwebview,它是Flutter插件,允许您添加内联WebView或打开应用程序内浏览器窗口,并且具有许多事件,方法和选项来控制WebView。 / p>

如果需要为每个请求添加自定义标头,则可以使用shouldOverrideUrlLoading事件(需要使用useShouldOverrideUrlLoading: true选项启用它)。

相反,如果您需要向WebView中添加cookie,则可以只使用CookieManager类(CookieManager.setCookie方法来设置cookie)。

下面是一个示例,该示例在WebView中设置一个cookie(名为ci_session),并为每个请求设置一个自定义标头(名为My-Custom-Header):

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