MCPcopy Index your code
hub / github.com/DethAriel/ng-recaptcha

github.com/DethAriel/ng-recaptcha @v13.2.1

Chat with this repo
repository ↗ · DeepWiki ↗ · release v13.2.1 ↗ · + Follow
172 symbols 302 edges 52 files 11 documented · 6% updated 2y agov13.2.1 · 2023-11-25★ 47718 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Angular component for Google reCAPTCHA

ng-recaptcha npm version

MIT licensed Build Status Coverage Status NPM downloads

A simple, configurable, easy-to-start component for handling reCAPTCHA v2 and v3.

Table of contents

  1. Installation
  2. Basic Usage
  3. reCAPTCHA v3 Usage
  4. Playground
  5. Working with @angular/forms
  6. API
  7. Input Options
  8. Events
  9. Methods
  10. Angular version compatibility
  11. Examples
  12. Configuring the component globally
  13. Specifying a different language
  14. Handling errors
  15. Loading the reCAPTCHA API by yourself
  16. Usage with required in forms
  17. Working with invisible reCAPTCHA
  18. Resizing
  19. SystemJS configuration
  20. Loading from a different location
  21. Specifying nonce for Content-Security-Policy
  22. Listening for all actions with reCAPTCHA v3
  23. Loading reCAPTCHA keys asynchronously
  24. Hiding reCAPTCHA badge

Installation

The easiest way is to install through yarn or npm:

yarn add ng-recaptcha
npm i ng-recaptcha --save

Basic Usage (see in action)

The below applies to reCAPTCHA v2, for basic usage with reCAPTCHA v3 scroll down to here.

To start with, you need to import the RecaptchaModule (more on that later):

// app.module.ts
import { RecaptchaModule } from "ng-recaptcha";
// if you need forms support:
// import { RecaptchaModule, RecaptchaFormsModule } from 'ng-recaptcha';
import { BrowserModule } from "@angular/platform-browser";
import { MyApp } from "./app.component.ts";

@NgModule({
  bootstrap: [MyApp],
  declarations: [MyApp],
  imports: [
    BrowserModule,
    RecaptchaModule,
    // RecaptchaFormsModule, // if you need forms support
  ],
})
export class MyAppModule {}

Once you have done that, the rest is simple:

// app.component.ts
import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  template: `<re-captcha (resolved)="resolved($event)" siteKey="YOUR_SITE_KEY"></re-captcha>`,
})
export class MyApp {
  resolved(captchaResponse: string) {
    console.log(`Resolved captcha with response: ${captchaResponse}`);
  }
}
// main.ts
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { MyAppModule } from "./app.module.ts";

platformBrowserDynamic().bootstrapModule(MyAppModule);

reCAPTCHA v3 Usage (see in action)

reCAPTCHA v3 introduces a different way of bot protection. To work with v3 APIs, ng-recaptcha provides a service (as opposed to a component). To start with, you need to import the RecaptchaV3Module and provide your reCAPTCHA v3 site key using RECAPTCHA_V3_SITE_KEY injection token:

import { BrowserModule } from "@angular/platform-browser";
import { RECAPTCHA_V3_SITE_KEY, RecaptchaV3Module } from "ng-recaptcha";

import { MyApp } from "./app.component.ts";

@NgModule({
  bootstrap: [MyApp],
  declarations: [MyApp],
  imports: [BrowserModule, RecaptchaV3Module],
  providers: [{ provide: RECAPTCHA_V3_SITE_KEY, useValue: "<YOUR_SITE_KEY>" }],
})
export class MyAppModule {}

In order to execute a reCAPTCHA v3 action, import the ReCaptchaV3Service into your desired component:

import { ReCaptchaV3Service } from 'ng-recaptcha';

@Component({
  selector: 'recaptcha-demo',
  template: `
    <button (click)="executeImportantAction()">Important action</button>
  `,
})
export class RecaptchaV3DemoComponent {
  constructor(
    private recaptchaV3Service: ReCaptchaV3Service,
  ) {
  }

  public executeImportantAction(): void {
    this.recaptchaV3Service.execute('importantAction')
      .subscribe((token) => this.handleToken(token));
  }

As always with subscriptions, please don't forget to unsubscribe.

❗️ Important note: If your site uses both v2 and v3, then you should always provide RECAPTCHA_V3_SITE_KEY (even in modules that only rely on v2 functionality). This will prevent bugs in your code by allowing ng-recaptcha to follow reCAPTCHA development guidelines properly (this one in particular).

A more advanced v3 usage scenario includes listening to all actions and their respectively emitted tokens. This is covered later on this page.

Playground

You can also play with this Stackblitz demo to get a feel of how this component can be used.

Working with @angular/forms

There are two modules available for you:

import { RecaptchaModule, RecaptchaFormsModule } from "ng-recaptcha";

If you want your <re-captcha> element to work correctly with [(ngModel)] directive, you need to import the RecaptchaFormsModule into your application module (pretty much like with Angular own '@angular/forms' module).

API

Input Options

The component supports this options:

  • siteKey
  • theme
  • type
  • size
  • tabIndex
  • badge

They are all pretty well described either in the reCAPTCHA docs, or in the invisible reCAPTCHA docs, so I won't duplicate it here.

One additional option that component accepts is errorMode. You can learn more about it in the Handling errors section below.

Besides specifying these options on the component itself, you can provide a global <re-captcha> configuration - see Configuring the component globally section below.

Events

  • resolved(response: string). Occurs when the captcha resolution value changed. When user resolves captcha, use response parameter to send to the server for verification. This parameter is equivalent to calling grecaptcha.getResponse.

If the captcha has expired prior to submitting its value to the server, the component will reset the captcha, and trigger the resolved event with response === null.

  • errored(errorDetails: RecaptchaErrorParameters). Occurs when reCAPTCHA encounters an error (usually a connectivity problem) if and only if errorMode input has been set to "handled". errorDetails is a simple propagation of any arguments that the original error-callback has provided, and is documented here for the purposes of completeness and future-proofing. This array will most often (if not always) be empty. A good strategy would be to rely on just the fact that this event got triggered, and show a message to your app's user telling them to retry.

Methods

  • reset(). Performs a manual captcha reset. This method might be useful if your form validation failed, and you need the user to re-enter the captcha.
  • execute(). Executes the invisible recaptcha. Does nothing if component's size is not set to "invisible". See Invisible reCAPTCHA developers guide for more information.

Angular version compatibility

ng-recaptcha version Supported Angular versions
13.x.x 17.x.x
12.x.x 16.x.x
11.x.x 15.x.x
10.x.x 14.x.x
9.x.x 13.x.x
8.x.x 12.x.x
7.x.x 11.x.x
⬆️ Starting with ng-recaptcha@7, only one version of Angular will be supported
6.x.x 6.x.x \|\| 7.x.x \|\| 8.x.x \|\| 9.x.x \|\| 10.x.x
5.x.x 6.x.x \|\| 7.x.x \|\| 8.x.x
4.x.x 6.x.x \|\| 7.x.x
3.x.x 4.x.x \|\| 5.x.x
2.x.x 2.x.x \|\| 4.x.x
1.x.x 2.x.x

Examples

Configuring the component globally (see in action)

Some properties are global - including siteKey, size, and others. You can provide them at the module-level using the RECAPTCHA_SETTINGS provider:

import { RECAPTCHA_SETTINGS, RecaptchaSettings } from "ng-recaptcha";

@NgModule({
  providers: [
    {
      provide: RECAPTCHA_SETTINGS,
      useValue: { siteKey: "<YOUR_KEY>" } as RecaptchaSettings,
    },
  ],
})
export class MyModule {}

Global properties can be overridden on a case-by-case basis - the values on the <re-captcha> component itself take precedence over global settings.

Specifying a different language (see in action)

<re-captcha> supports various languages. By default recaptcha will guess the user's language itself (which is beyond the scope of this lib). But you can override this behavior and provide a specific language to use by setting the "hl" search param in the onBeforeLoad hook. Note, that the language setting is global, and cannot be set on a per-captcha basis.

A good way to synchronize reCAPTCHA language with the rest of your application is relying on LOCALE_ID value like so:

import { LOCALE_ID } from "@angular/core";
import { RECAPTCHA_LOADER_OPTIONS } from "ng-recaptcha";

@NgModule({
  providers: [
    {
      provide: RECAPTCHA_LOADER_OPTIONS,
      useFactory: (locale: string) => ({
        onBeforeLoad(url) {
          url.searchParams.set("hl", locale);

          return { url };
        },
      }),
      deps: [LOCALE_ID],
    },
  ],
})
export class MyModule {}

Alternatively, a specific language can be provided like so:

import { RECAPTCHA_LOADER_OPTIONS } from "ng-recaptcha";

@NgModule({
  providers: [
    {
      provide: RECAPTCHA_LOADER_OPTIONS,
      useValue: {
        onBeforeLoad(url) {
          url.searchParams.set("hl", "fr"); // use French language

          return { url };
        },
      },
    },
  ],
})
export class MyModule {}

You can find the list of supported languages in reCAPTCHA docs.

Handling errors

Sometimes reCAPTCHA encounters an error, which is usually a network connectivity problem. It cannot continue until connectivity is restored. By default, reCAPTCHA lets the user know that an error has happened (it's a built-in functionality of reCAPTCHA itself, and this lib is not in control of it). The downside of such behavior is that you, as a developer, don't get notified about this in any way. Opting into such notifications is easy, but comes at a cost of assuming responsibility for informing the user that they should retry. Here's how you would do this:

```typescript import { Component } from "@angular/core";

@Component({ selector: "my-app", template: `<re-captcha (resolved)="resolved($event)" (errored)="errore

Extension points exported contracts — how you extend this code

OnExecuteData (Interface)
(no doc)
projects/ng-recaptcha/src/lib/recaptcha-v3.service.ts
PageSettings (Interface)
(no doc)
projects/demo/src/app/demo-wrapper/demo-wrapper.component.ts
OnExecuteErrorData (Interface)
(no doc)
projects/ng-recaptcha/src/lib/recaptcha-v3.service.ts
NavLink (Interface)
(no doc)
projects/demo/src/app/demo-wrapper/demo-wrapper.component.ts
Window (Interface)
(no doc)
projects/ng-recaptcha/src/lib/load-script.ts
FormModel (Interface)
(no doc)
projects/demo/src/app/examples/forms/forms-demo.component.ts
RecaptchaSettings (Interface)
(no doc)
projects/ng-recaptcha/src/lib/recaptcha-settings.ts
Chainable (Interface)
(no doc)
projects/demo/cypress/support/commands.ts

Core symbols most depended-on inside this repo

execute
called by 15
projects/ng-recaptcha/src/lib/recaptcha.component.ts
init
called by 14
projects/ng-recaptcha/src/lib/recaptcha-v3.service.ts
reset
called by 8
projects/ng-recaptcha/src/lib/recaptcha.component.ts
parseLangFromHref
called by 8
projects/demo/src/app/parse-lang-from-href.ts
assertConfigLoaded
called by 3
projects/demo/src/app/examples/config.service.ts
highlightRequire
called by 3
projects/demo/bin/file-gen.ts
executeActionWithSubject
called by 2
projects/ng-recaptcha/src/lib/recaptcha-v3.service.ts
ngOnDestroy
called by 2
projects/ng-recaptcha/src/lib/recaptcha.component.ts

Shape

Method 65
Class 58
Function 40
Interface 9

Languages

TypeScript100%

Modules by API surface

projects/ng-recaptcha/src/lib/recaptcha.component.ts13 symbols
projects/ng-recaptcha/src/lib/test-utils/mock-grecaptcha.spec.ts11 symbols
projects/ng-recaptcha/src/lib/recaptcha-v3.service.ts11 symbols
projects/ng-recaptcha/src/lib/recaptcha-loader.service.spec.ts9 symbols
projects/demo/src/app/demo-wrapper/demo-wrapper.component.ts9 symbols
projects/demo/src/app/examples/config.service.ts8 symbols
projects/ng-recaptcha/src/lib/recaptcha-value-accessor.directive.ts7 symbols
projects/demo/src/app/examples/v3/v3-demo.component.ts7 symbols
projects/ng-recaptcha/src/lib/recaptcha-value-accessor.directive.spec.ts6 symbols
projects/demo/bin/file-gen.ts6 symbols
projects/ng-recaptcha/src/lib/recaptcha-v3.service.spec.ts5 symbols
projects/ng-recaptcha/src/lib/recaptcha-loader.service.ts5 symbols

For agents

$ claude mcp add ng-recaptcha \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact