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

Flutter WebView:如何为loadHtmlString设置域名解决reCAPTCHA错误?

Flutter WebView加载含Google reCAPTCHA的HTML时域名验证错误

用户使用Flutter的WebViewController调用loadHtmlString加载包含Google reCAPTCHA的HTML代码,出现域名验证错误,具体代码和错误如下:

原HTML代码

<html>
  <head>
    <script src="https://www.google.com/recaptcha/api.js" async defer ></script>
  </head>
  <body>
      <div class="g-recaptcha" data-sitekey="my_key">
      </div>
  </body>
</html>

Flutter加载代码

WebViewController controller = WebViewController()
      ..loadHtmlString(html);
WebViewWidget(controller: controller);

报错信息

ERROR for site owner: Invalid domain for site key.

解决方案

loadHtmlString本身没有直接设置域名的参数,但可以通过以下两种方式解决该问题:

  • 改用本地文件加载
    将HTML内容保存为本地资源文件(例如assets/recaptcha.html),通过loadRequest加载文件URL,同时在Google reCAPTCHA控制台的允许域名列表中添加localhost或对应平台的本地文件域名(如Android的file://)。示例代码:

    final controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(Uri.parse('asset:///assets/recaptcha.html'));
    
  • 调整reCAPTCHA加载逻辑并配置允许域名
    loadHtmlString加载的内容默认origin为about:blank,先在Google reCAPTCHA控制台将about:blank添加到允许域名列表,然后修改HTML代码,使用手动渲染方式加载reCAPTCHA:

    <html>
      <head>
        <script src="https://www.google.com/recaptcha/api.js?render=你的sitekey" async defer></script>
        <script>
          grecaptcha.ready(function() {
            grecaptcha.render('captcha-container', {
              'sitekey': '你的sitekey'
            });
          });
        </script>
      </head>
      <body>
        <div id="captcha-container"></div>
      </body>
    </html>
    

    同时确保Flutter WebView启用JavaScript:

    final controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadHtmlString(html);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:46:34