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

AstroJS中HCaptcha事件函数看似无响应的问题解决

hCaptcha在Astro中事件不触发的问题及解决

问题描述

在Astro项目中使用@hcaptcha/react-hcaptcha组件时,onVerify、onOpen等事件始终未触发,但相同代码在纯React环境中可正常运行,初步推测问题出在Astro的组件加载机制上。

最初的index.astro代码如下:

---
import HCaptcha from "@hcaptcha/react-hcaptcha";

function handleVerificationSuccess(token, ekey) {
  console.log("Token:", token);
  console.log("Ekey:", ekey);
}
---

<!doctype html>
<html lang="sr">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <div>
      <HCaptcha
        client:load
        sitekey={import.meta.env.PUBLIC_MY_SITE_KEY}
        onVerify={(token, ekey) => handleVerificationSuccess(token, ekey)}
        onOpen={() => console.log("it's open")}
      />
    </div>
  </body>
</html>

开发者工具中出现以下警告,但不确定是否与问题相关:

Partitioned cookie or storage access was provided to https://newassets.hcaptcha.com...... because it is loaded in the third-party context and dynamic state partitioning is enabled.

Some cookies are misusing the recommended “SameSite“ attribute

Cookie “__cflb” has been rejected because it is in a cross-site context and its “SameSite” is “Lax” or “Strict”. https://api.hcaptcha.com/getcaptcha/my_sitekey

Cookie “__cflb” has been rejected because it is in a cross-site context and its “SameSite” is “Lax” or “Strict”. https://api.hcaptcha.com/checkcaptcha/my_site_key/long_array_of_numbers_and_letters

更新1:拆分组件尝试

尝试将HCaptcha组件及相关逻辑移入单独的verification.jsx组件中,但问题依旧。

index.astro代码:

---
import Verification from "../components/verification.jsx";
---

<!doctype html>
<html lang="sr">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <div>
      <Verification client:load />
    </div>
  </body>
</html>

verification.jsx代码:

import React from 'react';
import HCaptcha from "@hcaptcha/react-hcaptcha";

const Verification = () => {

  function handleVerificationSuccess(token, ekey) {
    console.log("Token:", token);
    console.log("Ekey:", ekey);
  }

  return (
      <div>
       <HCaptcha
       sitekey={import.meta.env.PUBLIC_MY_SITE_KEY}
       onVerify={(token, ekey) => handleVerificationSuccess(token, ekey)}
       onOpen={() => console.log("it's open")}
     />
      </div>
  );
};

export default Verification;

更新2:问题解决

最终发现是浏览器开发者工具的日志被隐藏,将代码迁移到单独JSX组件后,onVerify、onOpen等事件实际已正常触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:13:22