Flutter webview 拦截并为所有请求添加标头

Ibr*_*him 2 android webview interceptor flutter

使用 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);
});
Run Code Online (Sandbox Code Playgroud)

为了保持会话进行,我需要为所有请求添加相同的标头,而不仅仅是初始请求。有没有办法拦截所有请求并通过向它们添加标头来修改它们?

我发现的最接近的事情是navigationDelegate 但它只返回一个NavigationDecision在我的情况下没有用的。

Lor*_*lli 8

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

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

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

下面是一个示例,它ci_session在您的 WebView中设置了一个 cookie(命名),并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;
            },
          ))
        ])),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)