You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web中reCaptcha V2内容尺寸变化时如何调整HtmlElementView大小

Flutter Web reCaptcha v2 自适应高度解决方案

核心逻辑是通过网页侧与Flutter侧的跨端通信,监听reCaptcha容器的高度变化,动态调整承载HtmlElementView的容器高度,具体修改步骤如下:

1. 修改Flutter侧代码

把SizedBox的固定高度替换为可响应状态更新的变量,同时添加对iframe发来的高度消息的监听:

import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'dart:html' as html;

class GCaptchaPlugin extends StatefulWidget {
  const GCaptchaPlugin({Key? key}) : super(key: key);

  @override
  _GCaptchaPluginState createState() => _GCaptchaPluginState();
}

class _GCaptchaPluginState extends State<GCaptchaPlugin> {
  final String createdViewId = 'recaptcha_view';
  // 动态高度变量,初始值为reCaptcha默认闭合高度
  double _captchaHeight = 120.0;

  @override
  void initState() {
    super.initState();
    // 监听网页侧发来的高度调整消息
    html.window.addEventListener('message', (event) {
      final html.MessageEvent msgEvent = event as html.MessageEvent;
      // 校验消息类型为captcha高度更新
      if (msgEvent.data['type'] == 'captcha_height_change') {
        setState(() {
          // 额外加少量冗余高度避免边框裁切
          _captchaHeight = msgEvent.data['height'] + 8;
        });
      }
    });

    ui.platformViewRegistry.registerViewFactory(
        createdViewId,
        (int viewId) => html.IFrameElement()
          ..style.height = '100%'
          ..style.width = '100%'
          ..src = "/assets/html/recaptcha.html"
          ..style.border = 'none'
          ..allowFullscreen = true);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Expanded(
          child: SizedBox(
            // 替换为动态高度
            height: _captchaHeight,
            child: HtmlElementView(
              viewType: createdViewId,
            ),
          ),
        ),
      ],
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
    );
  }
}

2. 修改本地recaptcha.html代码

在reCaptcha渲染的网页中添加高度变化监听,高度变化时主动向父页面(Flutter Web侧)发送消息:

<!-- 原有reCaptcha引入、渲染逻辑不变,新增以下JS代码 -->
<script>
let lastHeight = 0;
// 定时检测容器高度变化
setInterval(() => {
  const captchaContainer = document.querySelector('.g-recaptcha')?.parentElement;
  if (captchaContainer) {
    const currentHeight = captchaContainer.offsetHeight;
    if (currentHeight !== lastHeight) {
      lastHeight = currentHeight;
      // 向父页面发送高度更新消息
      window.parent.postMessage({
        type: 'captcha_height_change',
        height: currentHeight
      }, '*');
    }
  }
}, 200);
</script>

内容的提问来源于stack exchange,提问作者MicroDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:45:00