Flutter WebView如何实现验证码自动填充

在Flutter中使用WebView加载带有验证码的页面时,如何实现自动填充验证码的功能?目前尝试了JavaScript注入和监听页面内容变化的方法,但都无法成功获取或自动填写验证码。请问有没有可靠的实现方案或插件推荐?

2 回复

使用flutter_inappwebview插件,在WebView中注入JavaScript代码监听输入框变化,通过controller.evaluateJavascript自动填充验证码。需注意跨域限制和用户隐私。

更多关于Flutter WebView如何实现验证码自动填充的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter WebView中实现验证码自动填充,可以通过以下步骤实现:

核心实现方案

1. 使用webview_flutter插件

dependencies:
  webview_flutter: ^4.4.2

2. 主要实现代码

import 'package:webview_flutter/webview_flutter.dart';

class CaptchaAutoFillWebView extends StatefulWidget {
  final String verificationCode;
  
  const CaptchaAutoFillWebView({super.key, required this.verificationCode});

  @override
  State<CaptchaAutoFillWebView> createState() => _CaptchaAutoFillWebViewState();
}

class _CaptchaAutoFillWebViewState extends State<CaptchaAutoFillWebView> {
  late final WebViewController controller;

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(Uri.parse('你的网页URL'))
      ..addJavaScriptChannel(
        'CaptchaChannel',
        onMessageReceived: (JavaScriptMessage message) {
          // 处理来自网页的消息
        },
      );
  }

  // 自动填充验证码
  void autoFillCaptcha() {
    String jsCode = '''
      // 查找验证码输入框(根据实际网页结构调整选择器)
      const captchaInput = document.querySelector('#captcha-input') || 
                          document.querySelector('input[type="text"]') ||
                          document.querySelector('input[name="captcha"]');
      
      if (captchaInput) {
        captchaInput.value = '${widget.verificationCode}';
        // 触发输入事件确保网页能检测到值变化
        captchaInput.dispatchEvent(new Event('input', { bubbles: true }));
        captchaInput.dispatchEvent(new Event('change', { bubbles: true }));
      }
    ''';
    
    controller.runJavaScript(jsCode);
  }

  @override
  Widget build(BuildContext context) {
    return WebViewWidget(controller: controller);
  }
}

3. 触发自动填充的时机

// 在页面加载完成后自动填充
controller.setNavigationDelegate(NavigationDelegate(
  onPageFinished: (String url) {
    // 延迟执行确保DOM完全加载
    Future.delayed(const Duration(milliseconds: 1000), () {
      autoFillCaptcha();
    });
  },
));

关键注意事项

  1. 选择器适配:需要根据目标网页的HTML结构调整CSS选择器
  2. 执行时机:确保在页面完全加载后执行JavaScript
  3. 事件触发:不仅要设置value,还要触发相应事件
  4. 安全性:避免在JavaScript中暴露敏感信息

替代方案

如果上述方法不适用,可以考虑:

  • 使用flutter_inappwebview插件,提供更多WebView控制功能
  • 与服务端配合,通过接口直接传递验证码
  • 使用浏览器插件方式处理

根据你的具体需求和目标网页结构选择合适的实现方式。

回到顶部