npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@aardpro/captcha-browser

v1.0.1

Published

点击式行为验证码前端库 - Browser implementation

Readme

@aardpro/captcha-browser

点击式行为验证码前端库 - Browser implementation

功能特点

  • 🎯 点击式验证:用户按顺序点击图片上的字符
  • 🔌 开箱即用:简洁的 API 设计
  • 🎨 可定制:支持自定义标记样式
  • 📦 TypeScript:完整的类型定义
  • 🚀 零依赖:纯原生 JavaScript 实现
  • 🔧 易于集成:适用于任何前端框架

安装

# npm
npm install @aardpro/captcha-browser

# yarn
yarn add @aardpro/captcha-browser

# pnpm
pnpm add @aardpro/captcha-browser

# bun
bun add @aardpro/captcha-browser

快速开始

1. 基本使用

import { Captcha } from '@aardpro/captcha-browser';

const captcha = new Captcha({
  container: '#captcha-container',
});

// 生成验证码
await captcha.generate();

// 验证验证码
const result = await captcha.verify();

2. 配置选项

// 定义 API 函数(自行实现业务逻辑)
async function generateCaptcha() {
  const response = await fetch('/api/captcha');
  return await response.json();
}

async function verifyCaptcha(clicks, token) {
  const response = await fetch('/api/verify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ input: clicks, token }),
  });
  return await response.json();
}

const captcha = new Captcha({
  container: '#captcha-container',
  width: 400,
  generateCaptcha,
  verifyCaptcha,
  markerStyle: {
    color: '#ff0000',
    size: 20,
    borderWidth: 2,
  },
});

2.1. 自定义 API 函数

您可以在函数中添加任意业务逻辑,如状态验证、权限检查、日志记录等:

async function generateCaptcha() {
  // 状态检查
  if (!userStore.isLoggedIn) {
    throw new Error('请先登录');
  }

  // 发起请求
  const response = await fetch('/api/captcha', {
    headers: {
      'Authorization': `Bearer ${userStore.token}`
    }
  });

  if (!response.ok) {
    throw new Error(`生成失败: ${response.statusText}`);
  }

  const data = await response.json();

  // 业务日志
  analytics.track('captcha_generated');

  return data;
}

async function verifyCaptcha(clicks, token) {
  const result = await myApiService.verifyCaptcha(clicks, token);

  // 记录验证日志
  analytics.track('captcha_verified', {
    success: result.data.valid,
    clickCount: clicks.length
  });

  return result;
}

const captcha = new Captcha({
  container: '#captcha-container',
  generateCaptcha,
  verifyCaptcha,
});

3. 事件监听

const captcha = new Captcha({
  container: '#captcha-container',
  
  onGenerate: (response) => {
    console.log('验证码生成成功', response);
  },

  onClick: (coordinate, allCoordinates) => {
    console.log('点击了', coordinate, '总共', allCoordinates.length);
  },

  onVerifySuccess: (response) => {
    console.log('验证通过!');
  },

  onVerifyError: (error) => {
    console.error('验证失败', error);
  },
});

4. 完整示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>验证码示例</title>
</head>
<body>
  <!-- 只需要一个容器,Captcha 类会自动创建完整的 UI -->
  <div id="captcha-container"></div>

  <script type="module">
    import { Captcha } from '@aardpro/captcha-browser';

    // 定义 API 函数
    async function generateCaptcha() {
      const response = await fetch('/api/captcha');
      if (!response.ok) {
        throw new Error(`生成失败: ${response.statusText}`);
      }
      return await response.json();
    }

    async function verifyCaptcha(clicks, token) {
      const response = await fetch('/api/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ input: clicks, token }),
      });
      if (!response.ok) {
        throw new Error(`验证失败: ${response.statusText}`);
      }
      return await response.json();
    }

    const captcha = new Captcha({
      container: '#captcha-container',
      generateCaptcha,
      verifyCaptcha,
      onVerifySuccess: () => alert('验证通过!'),
      onVerifyError: () => alert('验证失败!'),
    });

    // 页面加载时生成验证码
    await captcha.generate();
  </script>
</body>
</html>

API 文档

Captcha 类

构造函数

constructor(options: CaptchaOptions)

参数说明:

  • options.container (HTMLElement | string) - 容器元素或选择器(必需)
  • options.width (number) - 图片宽度,默认 400
  • options.generateCaptcha (function) - 生成验证码的函数(必需),返回 Promise<CaptchaGenerateResponse>
  • options.verifyCaptcha (function) - 验证验证码的函数(必需),接收点击坐标和 token,返回 Promise<CaptchaVerifyResponse>
  • options.markerStyle (object) - 标记样式配置
    • color (string) - 标记颜色,默认 '#667eea'
    • size (number) - 标记大小,默认 24
    • borderWidth (number) - 边框宽度,默认 2
  • options.onGenerate (function) - 生成验证码成功回调
  • options.onGenerateError (function) - 生成验证码失败回调
  • options.onClick (function) - 点击图片回调
  • options.onVerifySuccess (function) - 验证成功回调
  • options.onVerifyError (function) - 验证失败回调
  • options.onRefresh (function) - 刷新回调

方法

generate()

生成新的验证码。

async generate(): Promise<CaptchaGenerateResponse>
verify()

验证用户点击的坐标。

async verify(): Promise<CaptchaVerifyResponse>
refresh()

刷新验证码(清除旧数据并生成新的)。

async refresh(): Promise<CaptchaGenerateResponse>
clearClicks()

清除所有点击记录。

clearClicks(): void
clearMarkers()

清除所有点击标记。

clearMarkers(): void
reset()

重置验证码状态。

reset(): void
getClicks()

获取当前点击坐标。

getClicks(): [number, number][]
getToken()

获取当前 token。

getToken(): string
destroy()

销毁实例,清理资源。

destroy(): void

开发

# 克隆仓库
git clone https://github.com/aardpro/captcha-browser.git

# 安装依赖
npm install

# 开发模式(运行 demo)
npm run dev

# 构建
npm run build

# 监听模式构建
npm run build:watch

发布到 npm

1. 更新版本号

使用 npm version 命令自动更新版本号(会同时更新 package.json 和 git tag):

# 补丁版本(bug 修复):1.0.0 -> 1.0.1
npm version patch

# 小版本(新功能):1.0.0 -> 1.1.0
npm version minor

# 大版本(破坏性更新):1.0.0 -> 2.0.0
npm version major

# 或指定具体版本
npm version 1.2.3

2. 构建

npm run build

3. 发布到 npm

# 首次发布或使用新账号
npm login

# 发布到 npm(公网)
npm publish -- access public

4. 推送 git 标签

git push origin master --tags

Demo

运行 demo 需要先启动后端服务器:

# 终端 1:启动后端服务器
cd aardpro-captcha-backend/server
npm install
npm start

# 终端 2:启动前端 demo
cd aardpro-captcha-browser
npm install
npm run dev

然后访问 http://localhost:3000

License

MIT