GithubHelp home page GithubHelp logo

dethariel / ng-recaptcha Goto Github PK

View Code? Open in Web Editor NEW
468.0 15.0 121.0 4.16 MB

Angular component for Google reCAPTCHA

Home Page: https://dethariel.github.io/ng-recaptcha/

License: MIT License

TypeScript 87.60% JavaScript 3.71% CSS 2.62% HTML 6.02% Shell 0.05%
captcha google-recaptcha angular-recaptcha ng-recaptcha recaptcha-api

ng-recaptcha's Introduction

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. Working with @angular/forms
  4. API
  5. Angular version compatibility
  6. Examples

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:

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

@Component({
  selector: "my-app",
  template: `<re-captcha (resolved)="resolved($event)" (errored)="errored($event)" errorMode="handled"></re-captcha>`,
})
export class MyApp {
  resolved(captchaResponse: string) {
    console.log(`Resolved captcha with response: ${captchaResponse}`);
  }

  errored() {
    console.warn(`reCAPTCHA error encountered`);
  }
}

You can see this in action by navigating to either basic example demo or invisible demo and trying to interact with reCAPTCHA after setting the network to "Offline".

The errorMode input has two possible values -- "handled" and "default", with latter being the default as the name suggests. Not specifying errorMode, or setting it to anything other than "handled" will not invoke your (errored) callback, and will instead result in default reCAPTCHA functionality.

The (errored) callback will propagate all of the parameters that it receives from grecaptcha['error-callback'] (which might be none) as an array.

Loading the reCAPTCHA API by yourself (see in action)

By default, the component assumes that the reCAPTCHA API loading will be handled by the RecaptchaLoaderService. However, you can override that by providing your instance of this service to the Angular DI.

The below code snippet is an example of how such a provider can be implemented.

TL;DR: there should be an Observable that eventually resolves to a grecaptcha-compatible object (e.g. grecaptcha itself).

<script src="https://www.google.com/recaptcha/api.js?render=explicit&amp;onload=onloadCallback"></script>

<script>
  // bootstrap the application once the reCAPTCHA api has loaded
  function onloadCallback() {
    System.import("app").catch(function (err) {
      console.error(err);
    });
  }
</script>
import { RecaptchaLoaderService } from "ng-recaptcha";

@Injectable()
export class PreloadedRecaptchaAPIService {
  public ready: Observable<ReCaptchaV2.ReCaptcha>;

  constructor() {
    let readySubject = new BehaviorSubject<ReCaptchaV2.ReCaptcha>(grecaptcha);
    this.ready = readySubject.asObservable();
  }
}

@NgModule({
  providers: [
    {
      provide: RecaptchaLoaderService,
      useValue: new PreloadedRecaptchaAPIService(),
    },
  ],
})
export class MyModule {}

Usage with required in forms (see in action)

It's very easy to put <re-captcha> in an Angular form and have it required - just add the required attribute to the <re-captcha> element. Do not forget to import RecaptchaFormsModule from 'ng-recaptcha'!

@Component({
  selector: "my-form",
  template: ` <form>
    <re-captcha [(ngModel)]="formModel.captcha" name="captcha" required siteKey="YOUR_SITE_KEY"></re-captcha>
  </form>`,
})
export class MyForm {
  formModel = new MyFormModel();
}

A similar approach can be taken for reactive forms:

@Component({
  selector: "my-reactive-form",
  template: `
    <form [formGroup]="reactiveForm">
      <re-captcha formControlName="recaptchaReactive"></re-captcha>
      <button [disabled]="reactiveForm.invalid">Submit</button>
    </form>
  `,
})
export class MyReactiveForm {
  reactiveForm: FormGroup;

  ngOnInit() {
    this.reactiveForm = new FormGroup({
      recaptchaReactive: new FormControl(null, Validators.required),
    });
  }
}

Working with invisible reCAPTCHA (see in action)

Working with invisible reCAPTCHA is almost the same as with regular one. First, you need to provide the right size:

<re-captcha size="invisible" ...></re-captcha>

You will also need to invoke the "execute()" method manually. This can be done by either obtaining a reference to RecaptchaComponent via @ViewChild(), or by using inline template reference:

<re-captcha #captchaRef="reCaptcha" ...></re-captcha>
...
<button (click)="captchaRef.execute()">Submit</button>

Normally you would only submit a form when recaptcha response has been received. This can be achieved by reacting to (resolved) event and invoking submit logic when the captcha response is truthy (this will not try to submit the form when recaptcha response has expired). A sample implementation would look like this:

@Component({
  selector: "my-form",
  template: ` <form>
    <re-captcha
      #captchaRef="reCaptcha"
      siteKey="YOUR_SITE_KEY"
      size="invisible"
      (resolved)="$event && submit($event)"
    ></re-captcha>
    <button (click)="captchaRef.execute()">Submit</button>
  </form>`,
})
export class MyForm {
  public submit(captchaResponse: string): void {
    this.http.post({
      captcha: captchaResponse,
      /* ... */
    });
  }
}

Resizing

Making reCAPTCHA responsive is sometimes necessary, especially when working with mobile devices. You can use css-transforms to achieve that as in this StackOverflow answer, which is also ell-described in this blog post. You can also take a look at a live example of how this might be implemented. This boils down to

<div style="transform:scale(0.7);transform-origin:0;">
  <re-captcha></re-captcha>
</div>

SystemJS configuration

To configure the package to work with SystemJS, you would configure it approximately like that (assuming you've installed ng-recaptcha using npm):

// SystemJS config file
(function () {
  System.config({
    paths: {
      "npm:": "/node_modules/",
    },
    map: {
      "ng-recaptcha": "npm:ng-recaptcha",
    },
    packages: {
      "ng-recaptcha": { main: "./index.js" },
    },
  });
})();

Loading from a different location

Since "google.com" domain might be unavailable in some countries, reCAPTCHA core team has a solution for that - using "recaptcha.net" domain. You can configure the component to use that by using the onBeforeLoad hook of RECAPTCHA_LOADER_OPTIONS, for example:

import { RECAPTCHA_LOADER_OPTIONS } from "ng-recaptcha";

@NgModule({
  providers: [
    {
      provide: RECAPTCHA_LOADER_OPTIONS,
      useValue: {
        onBeforeLoad(_url) {
          return {
            url: new URL("https://www.recaptcha.net/recaptcha/api.js"), // use recaptcha.net script source for some of our users
          };
        },
      },
    },
  ],
})
export class MyModule {}

Specifying nonce for Content-Security-Policy

Per reCAPTCHA FAQ on CSP, the recommended approach for that is to supply nonce to the script tag. This is possible by providing the nonce as part of the onBeforeLoad hook of RECAPTCHA_LOADER_OPTIONS, for example

import { RECAPTCHA_LOADER_OPTIONS } from "ng-recaptcha";

@NgModule({
  providers: [
    {
      provide: RECAPTCHA_LOADER_OPTIONS,
      useValue: {
        onBeforeLoad(_url) {
          return {
            url,
            nonce: "<YOUR_NONCE_VALUE>",
          };
        },
      },
    },
  ],
})
export class MyModule {}

Listening for all actions with reCAPTCHA v3

More often than not you will need to only get a reCAPTCHA token with the action the user is currently taking, and submit it to the backend at that time. However, having a single listener for all events will be desirable.

There is an Observable exactly for that purpose: ReCaptchaV3Service.onExecute. It emits a value every time a token is received from reCAPTCHA. The shape of payload it operates on is defined via OnExecuteData interface:

interface OnExecuteData {
  action: string;
  token: string;
}

where action is the name of the action that has been executed, and token is what reCAPTCHA v3 provided when executing that action.

Here's how you would potentially set this up:

import { OnExecuteData, ReCaptchaV3Service } from "ng-recaptcha";

@Component({
  selector: "my-component",
  templateUrl: "./v3-demo.component.html",
})
export class MyComponent implements OnInit, OnDestroy {
  private subscription: Subscription;

  constructor(private recaptchaV3Service: ReCaptchaV3Service) {}

  public ngOnInit() {
    this.subscription = this.recaptchaV3Service.onExecute.subscribe((data: OnExecuteData) => {
      this.handleRecaptchaExecute(data.action, data.token);
    });
  }

  public ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

There are a couple things to keep in mind:

  • onExecute will trigger for all actions. If you only need to bulk-process some actions, and not others - you will have to apply filtering yourself.
  • onExecute observable will provide you with all the events emitted after you have subscribed to it - it doesn't keep references to the previously emitted actions. So make sure you add such a subscription as early in your code as you feel is necessary.
  • onExecute does not emit anything for when a grecaptcha error occurs. Use onExecuteError Observable for that.

Loading reCAPTCHA keys asynchronously

If your use-case needs to load the reCAPTCHA v2/v3 key from the backend (as opposed to specifying it in-code during build time), the Angular-idiomatic way to do that is by relying on APP_INITIALIZER. You can find an example of how this could look like below, and you can also consult the source code for the demo site.

// config.service.ts
import { Injectable } from "@angular/core";

@Injectable({
  providedIn: "root",
})
export class ConfigService {
  public recaptchaSiteKeyV2: string | null = null;
  public recaptchaSiteKeyV3: string | null = null;

  public async loadConfig(): Promise<void> {
    const { siteKeyV2, siteKeyV3 } = await fetchConfig(/* some API call */);
    this.recaptchaSiteKeyV2 = siteKeyV2;
    this.recaptchaSiteKeyV3 = siteKeyV3;
  }
}

// app.module.ts
import { APP_INITIALIZER, NgModule } from "@angular/core";
import { RECAPTCHA_SETTINGS, RecaptchaSettings, RECAPTCHA_V3_SITE_KEY } from "ng-recaptcha";

import { ConfigService } from "./config.service";

function appLoadFactory(config: ConfigService) {
  return () => config.loadConfig().then(() => console.log(`config resolved`, config));
}

@NgModule({
  providers: [
    {
      provide: RECAPTCHA_V3_SITE_KEY,
      useFactory: (config: ConfigService) => {
        return config.recaptchaSiteKeyV3;
      },
      deps: [ConfigService],
    },
    {
      provide: RECAPTCHA_SETTINGS,
      useFactory: (config: ConfigService): RecaptchaSettings => {
        return { siteKey: config.recaptchaSiteKeyV2 };
      },
      deps: [ConfigService],
    },
    {
      provide: APP_INITIALIZER,
      useFactory: appLoadFactory,
      deps: [ConfigService],
      multi: true,
    },
  ],
})
export class AppModule {}

Hiding reCAPTCHA badge

To start with, this is not strictly under ng-recaptcha library control. However, there is a way of doing so (albeit subject to certain conditions). Please refer to the FAQ section of reCAPTCHA documentation to get an idea of what you're required to do.

ng-recaptcha's People

Contributors

bbarry avatar deathbearbrown avatar dependabot[bot] avatar dethariel avatar dockleryxk avatar edimitchel avatar gkaran avatar impankratov avatar macbem avatar nosachamos avatar pedroqueiroga avatar sdorra avatar umairhm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng-recaptcha's Issues

Unclear example

Hi,

The module looks interesting. But when looking at the instructions is not actually clear how to set it up.

See below:

import { RecaptchaModule } from 'ng2-recaptcha';
import { BrowserModule }  from '@angular/platform-browser';

@NgModule({
  bootstrap: [MyApp],
  declarations: [MyApp],
  imports: [
    BrowserModule,
    RecaptchaModule.forRoot(), // Keep in mind the "forRoot"-magic nuances!
  ],
})
export class MyAppModule { }

There you bootstrap and declare MyApp which is never imported in this module.
(By the way, forRoot did not do it for me. I get Property 'forRoot' does not exist on type 'typeof ReCaptchaModule' error. I can raise a separate issue with more information if that'd help).

And then here:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `<recaptcha (resolved)="resolved($event)" siteKey="YOUR_SITE_KEY"></recaptcha>`,
}) export class MyApp {
    resolved(captchaResponse: string) {
        console.log(`Resolved captcha with response ${captchaResponse}:`);
    }
}

platformBrowserDynamic().bootstrapModule(MyAppModule);

You declare a new component and then export MyApp class. But at the end of this example you bootstrap your AppModule which is never imported in the example.

Can you please check on that? I've been trying to use it and I'm not sure what I'm missing.
So if you can have the instructions corrected, that'd be awesome.

Thanks.
Cheers!

Throwing error on build production

HI. I am developping a web app with ionic framework and when i try to build for production I get an error related to ng-recatcha.
Have you seen anything like this?
Error:
"Failed on type {"filePath":"/home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/ng-recaptcha/recaptcha/recaptcha-loader.service.d.ts","name":"RecaptchaLoaderService","members":[]} with error Error: Error encountered resolving symbol values statically. Expression form not supported (position 29:55 in the original .ts file), resolving symbol RecaptchaLoaderService in /home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/ng-recaptcha/recaptcha/recaptcha-loader.service.d.ts
Error: Error encountered resolving symbol values statically. Expression form not supported (position 29:55 in the original .ts file), resolving symbol RecaptchaLoaderService in /home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/ng-recaptcha/recaptcha/recaptcha-loader.service.d.ts
at positionalError (/home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/@angular/compiler/bundles/compiler.umd.js:24025:35)
at simplifyInContext (/home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/@angular/compiler/bundles/compiler.umd.js:23868:27)
at StaticReflector.simplify (/home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/@angular/compiler/bundles/compiler.umd.js:23882:13)
at StaticReflector.parameters (/home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/@angular/compiler/bundles/compiler.umd.js:23403:65)
at CompileMetadataResolver._getDependenciesMetadata (/home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/@angular/compiler/bundles/compiler.umd.js:14830:71)
at CompileMetadataResolver._getTypeMetadata (/home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/@angular/compiler/bundles/compiler.umd.js:14755:26)
at CompileMetadataResolver._getInjectableMetadata (/home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/@angular/compiler/bundles/compiler.umd.js:14741:21)
at CompileMetadataResolver.getProviderMetadata (/home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/@angular/compiler/bundles/compiler.umd.js:15031:40)
at /home/clovisjr/IonicProjs/PedidosOnline/Pedidos-V2-PizzariaBrasil-01/Pedidos-V2/node_modules/@angular/compiler/bundles/compiler.umd.js:14960:49
at Array.forEach ()"

Bug: Using ng-recaptcha in different components on the same page navigated by router-outlet

Hello,

I use router-outlet for navigation of some pages, each of them has a form using your invisible recaptcha.
When I get into one of these pages, and then move to another, I get this exception in my web browser's console:

Uncaught TypeError: Cannot read property 'render' of null
    at Vp (recaptcha__en.js:380)
    at Np.Hk (recaptcha__en.js:381)
    at ZoneDelegate.webpackJsonp.606.ZoneDelegate.invokeTask (zone.js:414)
    at Zone.webpackJsonp.606.Zone.runTask (zone.js:181)
    at ZoneTask.invoke (zone.js:476)
    at timer (zone.js:1491)

As far as I understand, it happens since the captcha tries to render itself again on the same page, and fails to do that in that previous element since it's not there anymore, because we just routed to a different page. Since there is no bug in recaptcha itself, I assume this issue should be taken care of in your component.

It sounds similar to this #35 issue, however I get a different exception.

Hopefully you can take a look into it and get it fixed and/or suggest me please I can go around it til then.

Thanks in advance!

DOMException when submitting a form

When I have <re-captcha> apart of the component when I submit a form I get the following error:

ERROR DOMException: Blocked a frame with origin "http://localhost:4200" from accessing a cross-origin frame.

I have the re-captcha component as part of the form:

<re-captcha siteKey="[removed]" formControlName="is_human"></re-captcha>

and only using it's value to validate the form. If it's not false, it is considered valid.

Angular packages not found while compiling

Hi,

maybe there is some issue with Angular 4.1. :(

while trying to normally import your package, compiller throwing these errors:

I am using a lot of angular2 packages in my project, but there is no issue with tham.

ERROR in /Applications/XAMPP/xamppfiles/htdocs/hudebnizkusebny/node_modules/ng-recaptcha/recaptcha/recaptcha-loader.service.d.ts (2,29): Cannot find module '@angular/core'.

ERROR in /Applications/XAMPP/xamppfiles/htdocs/hudebnizkusebny/node_modules/ng-recaptcha/recaptcha/recaptcha-loader.service.d.ts (3,28): Cannot find module 'rxjs/Observable'.

ERROR in /Applications/XAMPP/xamppfiles/htdocs/hudebnizkusebny/node_modules/ng-recaptcha/recaptcha/recaptcha.component.d.ts (2,64): Cannot find module '@angular/core'.

ERROR in /Applications/XAMPP/xamppfiles/htdocs/hudebnizkusebny/node_modules/ng-recaptcha/recaptcha/recaptcha.module.d.ts (1,37): Cannot find module '@angular/core'.

ERROR in ./src/app/app.module.ts
Module not found: Error: Can't resolve 'ng-recaptcha' in '/Applications/XAMPP/xamppfiles/htdocs/hudebnizkusebny/public/frontend/src/app'
 @ ./src/app/app.module.ts 61:0-47
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts

Best way to use ng-recaptcha with multiple forms

Hi have 2 components containing form on the same page, and I want to use invisible recaptcha in both of them.

I tried to use it twice, one recaptcha per component, and it looks to work almost, but I frequently get this JS error:

TypeError: null is not an object (evaluating 'a.style')
  at Th (/recaptcha/api2/r20170503135251/recaptcha__fr.js:130:152)
  at None (/recaptcha/api2/r20170503135251/recaptcha__fr.js:379:259)
  at None ([native code])
  at r (/vendor.e8ca299bdc7eb8a082ad.bundle.js:533:54252)
  at runTask (/polyfills.e973013abdce7c05a842.bundle.js:36:3206)

So, I guess it is probably better to create the recaptcha in my main component, then get a reference to it using @ViewChild, and pass it to each of my sub-components as an Input().

And when submitting a form in one of my component, manually trigger:

this.recaptchaRef.execute();

But infortunately, this method does not return an observable nor provide any callback mechanism, and make it tricky to execute the form action in my sub-component once the captcha has been resolved.

Any suggestion to solve my issue, or any plan to support such a scenario?

expired-callback not working as expected

The 'expired-callback' located within the "recaptcha.component.ts" is not working as expected - specifically, its not emitting a null via the "resolved" EventEmitter;

I verified that the call back is fired, ie: the following code does result in "reset()" being executed:

 'expired-callback': () => {
        this.zone.run(() => this.reset());
      },

However, within the reset method, the code never makes it past the "this.grecaptcha.getResponse" check; ie:

if (this.grecaptcha.getResponse(this.widget)) {
        // Only reset the captcha and emit an event in case if something would actually change.
        // That way we do not trigger "touching" of the control if someone does a "reset"
        // on a non-resolved captcha.
        this.grecaptcha.reset(this.widget);
        this.resolved.emit(null);
      }

It seems in every test I've performed, this method always returns an empty string after the recaptcha expires.

I'm not sure the best way to fix this; personally, I would think a good design would be to expose a new responseExpired EventEmitter, and let the developer subscribe to that to explicitly handle expiration; for example, perhaps we don't want to do an automatic reset of the recaptcha upon expiration.

How it work's with angular dynamic forms

Hi, I want to know, as it's not specify in the documentation, how this new version work's with angular dynamic forms.
With the previous version i was able to handle the recaptcha with a "formControlName", but now i've got an error. Is there a solution or i need to pass via the resolve function? Thank's

window is not defined ReferenceError: window is not defined

Hi, could you help me please with this error, some other package display the same message, what could be?

The error is in the /dist/main-server.js file.

I'm using a Net Core SPA project with angular 2, if you need more info tell me,
Thanks.

An angular variable/constant as sidekey?

I want to use the recaptcha multiple times, test it on my development with a different key as in production environment. In the latest angular 4 project created with angular/cli there is the following code within src/environment/environment.ts:

export const environment = {
  production: false,
  recaptcha_sitekey: '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI' // site key for testing.
};

Later for production there will be another code. My question is: How to use this constant in the sidekey-Parameter of ng-recaptcha? It would be hard to exchange all occurences for production code.

Question: compiling from source results in error due to Cannot find namespace 'ReCaptchaV2'

I'm compiling the library from the source, and tsc gives me these errors:

node_modules/ng2-recaptcha-src/recaptcha/recaptcha-loader.service.ts(15,41): error TS2503: Cannot find namespace 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha-loader.service.ts(17,28): error TS2503: Cannot find namespace 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha-loader.service.ts(17,28): error TS4031: Public property 'ready' of exported class has or is using private name 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha-loader.service.ts(33,12): error TS2339: Property 'ng2recaptchaloaded' does not exist on type 'Window'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha-loader.service.ts(34,41): error TS2304: Cannot find name 'grecaptcha'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha-loader.service.ts(36,56): error TS2503: Cannot find namespace 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha.component.ts(24,26): error TS2503: Cannot find namespace 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha.component.ts(24,26): error TS4031: Public property 'theme' of exported class has or is using private name 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha.component.ts(25,25): error TS2503: Cannot find namespace 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha.component.ts(25,25): error TS4031: Public property 'type' of exported class has or is using private name 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha.component.ts(26,25): error TS2503: Cannot find namespace 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha.component.ts(26,25): error TS4031: Public property 'size' of exported class has or is using private name 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha.component.ts(36,23): error TS2503: Cannot find namespace 'ReCaptchaV2'.
node_modules/ng2-recaptcha-src/recaptcha/recaptcha.component.ts(45,66): error TS2503: Cannot find namespace 'ReCaptchaV2'.

When I look into recaptcha.component.ts and recaptcha-loader.service.ts, I see uses of this namespace but this is never imported. I could not find where this is defined.

Where is this coming from?

Thank you!

Multiple reCAPTCHA components using custom provider error

I was able to create the custom provider to load the reCAPTCHA widget and allow for changing of the language. With two widgets on one page I get an error when loading:

The root looks to be that api.js is loaded multiple times.

Uncaught Error: ReCAPTCHA placeholder element must be empty
    at Object.Vp [as render] (recaptcha__en.js:384)
    at RecaptchaComponent.renderRecaptcha (recaptcha.component.js:69)
    at SafeSubscriber._next (recaptcha.component.js:18)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)
    at Subscriber._next (Subscriber.js:125)
    at Subscriber.next (Subscriber.js:89)
    at BehaviorSubject.Subject.next (Subject.js:55)
    at BehaviorSubject.next (BehaviorSubject.js:44)
    at window.ng2recaptchaloaded (locale-recaptcha-provider.ts:39)

After submitting and navigating away from the page,

ERROR Error: Uncaught (in promise): Error: Invalid ReCAPTCHA client id: 0
Error: Invalid ReCAPTCHA client id: 0
    at Object.Xp [as reset] (recaptcha__en.js:386)
    at recaptcha.component.js:63
    at ZoneDelegate.invoke (zone.js:381)
    at Zone.run (zone.js:141)
    at NgZone.runOutsideAngular (core.es5.js:4019)
    at RecaptchaComponent.grecaptchaReset (recaptcha.component.js:63)
    at RecaptchaComponent.ngOnDestroy (recaptcha.component.js:25)
    at callProviderLifecycles (core.es5.js:11145)
    at callElementProvidersLifecycles (core.es5.js:11114)
    at callLifecycleHooksChildrenFirst (core.es5.js:11098)
    at Object.Xp [as reset] (recaptcha__en.js:386)
    at recaptcha.component.js:63
    at ZoneDelegate.invoke (zone.js:381)
    at Zone.run (zone.js:141)
    at NgZone.runOutsideAngular (core.es5.js:4019)
    at RecaptchaComponent.grecaptchaReset (recaptcha.component.js:63)
    at RecaptchaComponent.ngOnDestroy (recaptcha.component.js:25)
    at callProviderLifecycles (core.es5.js:11145)
    at callElementProvidersLifecycles (core.es5.js:11114)
    at callLifecycleHooksChildrenFirst (core.es5.js:11098)
    at resolvePromise (zone.js:757)
    at resolvePromise (zone.js:728)
    at zone.js:805
    at ZoneDelegate.invokeTask (zone.js:414)
    at Object.onInvokeTask (core.es5.js:4119)
    at ZoneDelegate.invokeTask (zone.js:413)
    at Zone.runTask (zone.js:181)
    at drainMicroTaskQueue (zone.js:574)
    at HTMLFormElement.ZoneTask.invoke (zone.js:480)

"Cannot read property 'value' of null" when component is destroyed

This happens for both untouched captcha, and one that has been resolved.

TypeError: Cannot read property 'value' of null
at Object.mo [as getResponse] (https://www.gstatic.com/recaptcha/api2/r20170126104253/recaptcha__en_gb.js:298:137)
at RecaptchaComponent.reset (eval at ./node_modules/ng2-recaptcha/recaptcha/recaptcha.component.js (http://localhost:8000/app.1.js:11315:1), :38:33)
at RecaptchaComponent.ngOnDestroy (eval at ./node_modules/ng2-recaptcha/recaptcha/recaptcha.component.js (http://localhost:8000/app.1.js:11315:1), :33:14)

The captcha does not seem to work on v2

I can't seem to load the captcha and I get the following error
Uncaught (in promise): Error: DI Error

@angular/cli: 1.0.0
node: 6.9.5
os: win32 x64
@angular/common: 2.4.7
@angular/compiler: 2.4.7
@angular/core: 2.4.7
@angular/forms: 2.4.7
@angular/http: 2.4.7
@angular/material: 2.0.0-beta.2
@angular/platform-browser: 2.4.7
@angular/platform-browser-dynamic: 2.4.7
@angular/router: 3.4.7
@angular/cli: 1.0.0
@angular/compiler-cli: 2.4.7

AppModule

@NgModule({
    imports: [
        RecaptchaFormsModule

"Calling function 'RecaptchaLoaderService', function calls are not supp..." when build -prod

When I apply new language, it works fine in development environment

ng serve

But when I try to build prod, I get error

ng build -prod

ERROR in Error encountered resolving symbol values statically. Calling function 'RecaptchaLoaderService', function calls are not supp
replacing the function or lambda with a reference to an exported function, resolving symbol AppComponent in /Users/
src/app/app.component.ts, resolving symbol AppComponent in /Users/ang/src/app/app.compone

ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in '/Users/ang/src
@ ./src/main.ts 4:0-74
@ multi ./src/main.ts

Then I have to remove RecaptchaLoaderService.

Peerdependency error when using angular v2.4.4 with the latest version 1.5.0

hi,

The current release gives conflicts on dependencies

Angular 2.4.4 uses zone 0.7.2, but the current release of ng2-captcha uses 0.6.26.

Angular 2.4.4 release works with the ng2-translate release 1.4.0.

The difference i found is that zone v0.6.26 is added to the "peerdependency section" in "package.json"

This is the reason i get conflicts.

How can i resolve this issue? if i want to use the 1.5.0 version of ng2-translate

farhad

Invisible ReCaptcha Support

It seems to work for the most part by simply using "invisible" as the size attribute, but in order for it to work this package needs to implement grecaptcha.execute() so one may call it in the component and get the response token if needed.

Cannot find type definition file for 'grecaptcha' when running NG-XI18N

Hi,
when I try to extract translation strings from my app using ng-xi18n I'm getting this error in recaptcha module... How can I fix this?

./node_modules/.bin/ng-xi18n -p ./src/tsconfig.json Error: Error at /app/node_modules/ng2-recaptcha/recaptcha/recaptcha-loader.service.d.ts:1:1: Cannot find type definition file for 'grecaptcha'. Error at /app/node_modules/ng2-recaptcha/recaptcha/recaptcha-loader.service.d.ts:6:23: Cannot find namespace 'ReCaptchaV2'. Error at /app/node_modules/ng2-recaptcha/recaptcha/recaptcha.component.d.ts:1:1: Cannot find type definition file for 'grecaptcha'. Error at /app/node_modules/ng2-recaptcha/recaptcha/recaptcha.component.d.ts:10:12: Cannot find namespace 'ReCaptchaV2'. Error at /app/node_modules/ng2-recaptcha/recaptcha/recaptcha.component.d.ts:11:11: Cannot find namespace 'ReCaptchaV2'. Error at /app/node_modules/ng2-recaptcha/recaptcha/recaptcha.component.d.ts:12:11: Cannot find namespace 'ReCaptchaV2'. at UserError.Error (native) at new UserError (/app/node_modules/@angular/compiler-cli/node_modules/@angular/tsc-wrapped/src/tsc.js:22:34) at check (/app/node_modules/@angular/compiler-cli/node_modules/@angular/tsc-wrapped/src/tsc.js:73:15) at Tsc.typeCheck (/app/node_modules/@angular/compiler-cli/node_modules/@angular/tsc-wrapped/src/tsc.js:148:9) at /app/node_modules/@angular/compiler-cli/node_modules/@angular/tsc-wrapped/src/main.js:56:23 at process._tickCallback (internal/process/next_tick.js:103:7) at Module.runMain (module.js:606:11) at run (bootstrap_node.js:394:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:509:3 Extraction failed

Not found issues when using systemjs loader

I can't seem to make it work on systemjs. It finds ng2-recaptcha.noforms.js but it fails on following requests:

[1] 17.01.30 04:46:34 404 GET /node_modules/ng2-recaptcha/recaptcha/recaptcha.component
[1] 17.01.30 04:46:34 404 GET /node_modules/ng2-recaptcha/recaptcha/recaptcha-loader.service
[1] 17.01.30 04:46:34 404 GET /node_modules/ng2-recaptcha/recaptcha/recaptcha-noforms.module

My system.config.js has followinf line to load:

'ng2-recaptcha' : 'node_modules/ng2-recaptcha/ng2-recaptcha.noforms.js'

And like readme explains I call from module

import { RecaptchaModule } from 'ng2-recaptcha';

Any idea what is wrong?

Question: Webpack sample

I was wondering if someone could point to webpack sample somewhere! I cannot get it up and running in webpack 2.

`.forRoot()` not working

Hi,

The forRoot() method does not seem to work for me.

Here's my package.json:

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "My Project",
  "author": "Alphero",
  "contributors": [
    "Martín Martínez"
  ],
  "license": "UNLICENSED",
  "engines": {
    "node": ">=5.11.0",
    "npm": ">=3.8.6"
  },
  "scripts": {
    "reinstall": "rimraf node_modules && npm cache clean && npm install",
    "postinstall": "npm run typings",
    "typings": "typings install",
    "updatetypings": "typings ls | awk '$2 ~ /.+/ {print $2}' | xargs -I {} typings i dt~{} -SG",
    "prebuild": "rimraf dist",
    "build": "webpack --config config/webpack.prod.js --progress --profile --bail",
    "start": "webpack-dev-server --inline --progress --port 8079 --debug",
    "test": "karma start"
  },
  "keywords": [],
  "dependencies": {
    "@angular/common": "^2.0.1",
    "@angular/compiler": "^2.0.1",
    "@angular/core": "^2.0.1",
    "@angular/forms": "^2.0.1",
    "@angular/http": "^2.0.1",
    "@angular/platform-browser": "^2.0.1",
    "@angular/platform-browser-dynamic": "^2.0.1",
    "@angular/router": "^3.0.1",
    "angular2-recaptcha": "^0.3.4",
    "angular2-text-mask": "^2.1.0",
    "core-js": "^2.4.1",
    "headroom.js": "^0.9.3",
    "moment": "^2.17.0",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "autoprefixer": "^6.4.1",
    "browser-sync": "^2.16.0",
    "browser-sync-webpack-plugin": "^1.1.3",
    "css-loader": "^0.25.0",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "html-loader": "^0.4.4",
    "html-webpack-plugin": "^2.22.0",
    "jasmine-core": "^2.5.2",
    "karma": "^1.3.0",
    "karma-jasmine": "^1.0.2",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-spec-reporter": "0.0.26",
    "node-sass": "^3.10.0",
    "null-loader": "^0.1.1",
    "phantomjs-prebuilt": "^2.1.12",
    "postcss-loader": "^0.13.0",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.5.4",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "ts-loader": "^0.8.1",
    "tslint": "^3.15.1",
    "typescript": "^2.1.0-dev.20160926",
    "typings": "^1.4.0",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.16.1",
    "webpack-merge": "^0.14.1"
  }
}

I get the forRoot() is not a function error when going:

import { RecaptchaModule } from 'ng2-recaptcha';
import { BrowserModule }  from '@angular/platform-browser';

@NgModule({
  bootstrap: [MyApp],
  declarations: [MyApp],
  imports: [
    BrowserModule,
    RecaptchaModule.forRoot(), // Keep in mind the "forRoot"-magic nuances!
  ],
})
export class MyAppModule { }

Let me know if you need further information.

Cheers!
Martín.

ReCaptcha stealing the focus

After loading, recaptcha steals the focus from the focused field.
It should be able to override the method Recaptcha.focus_response_field .
Thanks.

How do I programmatically call resolve(event)?

I followed the guide on the front page for the invisible captcha.
I have referenced captcha in my .ts file
@ViewChild('captchaRef') public captcha: RecaptchaComponent;

and in my html I got this
<re-captcha #captchaRef="reCaptcha" size="invisible" siteKey="super-secret-key" (resolved)="resolved($event)"></re-captcha>

I am calling this.captcha.execute() to trigger execution but how do I call resolved(event)? When I try to assign this.captcha.resolved I get an EventEmitter. I am still pretty new to Angular so not sure what to do with that information. I tried using this.captcha.resolved.emit(); but what am I supposed to emit?

Auto submit form when validating invisible captcha

Hi,

So I don't know if there is a way to do this, but my problem is the following:

I'm using the invisible captcha on my login page. It goes like this

<div class="form-buttons">
        <div [class.enabled]="isValid() && !isPristine()" (click)="onSubmit();" class="submit-button">Login</div>
        <re-captcha [size]="'invisible'" site_key="6Lfz2xsUAAAAABf0KnVEpLdJptBScodnOYpliVPA"></re-captcha>

    </div>

And then

  @ViewChild(ReCaptchaComponent) captcha: ReCaptchaComponent;


    /**
     * If the form is valid, handle form submission here
     */
    onSubmit() {
        if (this.isValid()) {
            this.captcha.execute();
            let token = this.captcha.getResponse();
            if (token != "")
               this.signIn();
        }
    }

So my problem is that when / if the captcha activates, the user validates it, but then has to click on the submit button again.

Would you know a way to submit the form at the captcha validation ?

Thanks in advance :)

Second Page Loads, captcha not displayed

I've pulled in this component and it works great. I have run into one issue. When displaying the page with the captcha, then navigating away from this page and then going back, the captcha isn't shown on the second load of the page. No console errors or anything.

Any idea what could cause that?

Issue installing on angular 4.0.3

Trying to use "npm i ng-recaptcha --save"
when importing, i get a 404 error in the console

login:18 Error: (SystemJS) XHR error (404 Not Found) loading http://10.0.0.5:3000/ng-recaptcha Error: XHR error (404 Not Found) loading http://10.0.0.5:3000/ng-recaptcha at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://10.0.0.5:3000/node_modules/zone.js/dist/zone.js:1230:39) [<root>] at XMLHttpRequest.ZoneTask.invoke (http://10.0.0.5:3000/node_modules/zone.js/dist/zone.js:460:38) [<root>] Error loading http://10.0.0.5:3000/ng-recaptcha as "ng-recaptcha" from http://10.0.0.5:3000/app/app.module.js at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://10.0.0.5:3000/node_modules/zone.js/dist/zone.js:1230:39) [<root>] at XMLHttpRequest.ZoneTask.invoke (http://10.0.0.5:3000/node_modules/zone.js/dist/zone.js:460:38) [<root>] Error loading http://10.0.0.5:3000/ng-recaptcha as "ng-recaptcha" from http://10.0.0.5:3000/app/app.module.js

Tried to set defaultJsExtension to js, no difference...

Tried adding to the map in the systemjs.config.js:
'ng-recaptcha': 'npm:ng-recaptcha/index.js',

then i get a different error:
GET http://10.0.0.5:3000/node_modules/ng-recaptcha/recaptcha/recaptcha.component 404 (Not Found) for service and module as well :/

Am I missing something basic? red the instructions like 16 times already

captchaRef.execute() not working in invisible captcha

When I tried to debug the code I found this function:

RecaptchaComponent.prototype.execute = function () {
        if (this.size !== 'invisible') {
            return;
        }
        if (this.widget != null) {
            this.grecaptcha.execute(this.widget);
        }
    };

and the problem is that this.widget is undefined.
"ng-recaptcha": "^3.0.0",
What am I missing here ?

Errors in console

Recaptcha is working as expected in my app. however,
The following errors are thrown in to developer console:

`[default] C:\www\myapp\node_modules\ng2-recaptcha\recaptcha\recaptcha-loader.service.d.ts:3:22
Cannot find namespace 'ReCaptchaV2'.

[default] C:\www\myapp\node_modules\ng2-recaptcha\recaptcha\recaptcha.component.d.ts:9:11
Cannot find namespace 'ReCaptchaV2'.

[default] C:\www\myapp\node_modules\ng2-recaptcha\recaptcha\recaptcha.component.d.ts:10:10
Cannot find namespace 'ReCaptchaV2'.

[default] C:\www\myapp\node_modules\ng2-recaptcha\recaptcha\recaptcha.component.d.ts:11:10
Cannot find namespace 'ReCaptchaV2'.`

Thoughts on what is happening here?
I'd be happy to provide additional details if needed.

Angular2 - 2.0.0
[email protected]

Error in console, Template parse errors

HI,
I'm using anular-cli for this project.

  • Typescript version is 2.0.2
  • Angular 2.0.0
  • ng2-recaptcha 1.3.2

I've installed the typing using the following command

npm install @types/grecaptcha --save-dev

My root app module looks like this

import { BrowserModule } from '@angular/platform-browser';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { RecaptchaModule } from 'ng2-recaptcha';
import { routes } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserModule } from './user/user.module';
import { SharedModule } from './shared/shared.module';
import { ToasterModule, ToasterService } from 'angular2-toaster/angular2-toaster';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RecaptchaModule.forRoot(),
    ToasterModule,
    RouterModule.forRoot(routes, { useHash: true }),
    SharedModule.forRoot(),
    UserModule
  ],
  providers: [ToasterService],
  bootstrap: [AppComponent],
  exports: [],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }

After importing the module, in another module, UserModule (which is imported here) I'm using the element.

Thats when I'm getting this error in browser console.

zone.js:355Unhandled Promise rejection: Template parse errors:
'recaptcha' is not a known element:

If 'recaptcha' is an Angular component, then verify that it is part of this module.

If 'recaptcha' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.

After first time getting this message I added CUSTOM_ELEMENTS_SCHEMA in my root module as seen above, even after that I'm getting the same error.

Where I'm going wrong?

Thanks..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.