Issues with Google/Firebase reCaptcha not functioning properly in an Angular environment

Just diving into the new Firebase phone authentication documentation. They've added a recaptcha as an extra security measure against spam. The js documentation specifies that the recaptcha should be injected into the DOM using this code:

window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');

But for some reason, I can't seem to get it working in AngularJS. I tried replacing window. with $window and made sure it was accessible in my controller, but still no luck.

If anyone has any tips or pointers on how to make this work, I would really appreciate it.

This is the javascript documentation that I've been referring to: https://firebase.google.com/docs/auth/web/phone-auth

Answer №1

In a discussion thread on the GitHub repository, I addressed the topic of supporting PhoneNumber Auth: Support for PhoneNumber Auth #990

Here is a simple solution to sign in via phone and activate the Recaptcha:

UPDATE: (Issue Resolved)

I successfully managed to sign in via mobile from an Angular application! To use ReCaptcha as a widget, ensure that the containing div is created during object initialization.

I personally prefer using the 'invisible' method, so I added an empty div to my HTML page:

<div id="phone-sign-in-recaptcha"></div>

Within the ngOnInit() function, I initialized it as follows:

window['phoneRecaptchaVerifier'] = new firebase.auth.RecaptchaVerifier('phone-sign-in-recaptcha', {
  'size': 'invisible',
  'callback': function(response) {
    // Actions after reCAPTCHA verification
  },
  'expired-callback': function() {
    // Reset reCAPTCHA?
  }
});

The form submit function triggered upon successful recaptcha completion is:

this.auth.signInWithPhoneNumber(phoneNumber,     window['phoneRecaptchaVerifier']).then(function(confirmationResult){
  var code = prompt('A code has been sent to ' + phoneNumber + ', please enter it here', "");
  if (code) {
    confirmationResult.confirm(code).then(function (result) {
      // User signed in successfully.
      // Reset reCAPTCHA?
      // ...
    }).catch(function (error) {
      // User couldn't sign in (invalid code?)
      // Reset reCAPTCHA?
      // ...
    });
  }
}).catch(function(error){
  console.log(error.message);
});

To access the global variable grecaptcha for calling grecaptcha.reset([widgetId]) when needed (e.g., on recaptcha expiry or sign-in error), follow these steps:

npm install @types/grecaptcha --save

Then, declare the variable just below your imports in the component module where the recaptcha is implemented: declare var grecaptcha: any;

In my code, I replace the comment // Reset reCAPTCHA? with this call:

    window['phoneRecaptchaVerifier'].render().then(function(widgetId) {
      grecaptcha.reset(widgetId);
    });

Everything now works smoothly!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the benefits of sticking with Express versus transitioning to a combination of JavaScript and HTML?

Recently, I've been developing a web application that involves taking user input to make modifications to files on the server side. The main logic for this project is built in node.js and operates via command line, with the rest of the site being deve ...

Encountering a problem with Firebase while offline. The error message "FirebaseError: Firebase App named '[DEFAULT]' already exists with different options or config." is appearing

I've been having some trouble integrating Firebase into my app using the useFireBaseAuth hook. Everything works smoothly when there's an active internet connection, but I'm facing issues when offline. An error message shows up: Server Error ...

Upload files either one at a time or in bulk

Encountering an issue with file upload functionality. When uploading multiple files at once, there are no problems. However, when uploading single files one at a time, each new upload overrides the previous one. Looking for a solution to this problem. Be ...

The functionality of loading JSON is not working properly in ePub3

Currently, I am working on a project involving the creation of an ePub3 eBook. One of the exciting features I have successfully integrated is three.js to showcase some models. My next goal is to develop 'hotspot' elements (small cubes that users ...

Showing ng-repeat values in a modal

I am having trouble displaying values in a bootstrap modal when clicking on a specific story from a list of stories with images, content, and titles using ng-repeat. I have tried calling the function showStories(), but it is not working as expected. The va ...

Utilizing JSON data to populate a modal window in HTML

How can I incorporate JSON data into an HTML modal window? I have a set of 12 buttons, and when a user clicks on one, I want to display the corresponding month's information from a JSON file. let myJson; $(`button`).on(`click`, function() { let ...

Utilizing Core-TransitionEnd in Polymer: A Beginner's Guide

After a ripple animation on an item has executed, I would like to run a function. Currently, I am using the following code: <post-card id="card1"> <img width="70" height="70" src="../images/start.png"> <h2>P ...

Tips for transferring values from your application to the adapter in IBM Worklight

I am looking for a way to transfer parameters from the application to the adapter, where I want users to provide these options. Currently, I am passing the parameters in the adapter code like so: function getFeeds() { WL.Logger.debug("inside ...

Issue with the close button on ngb-alert not functioning properly

As I develop my website, I have incorporated an ngb-alert component to display an alert message to users upon login. While the alert itself is functioning properly, I have encountered an issue with the close button being misaligned, and I am struggling to ...

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

Wondering how to go back to the default locale in Next.js?

Within my Next.js application, I have successfully implemented the next-i18next module for multi-language support. The app currently supports two languages: English and Arabic, with English set as the default. To allow users to toggle between languages, I ...

Having issues with Npm installation not finishing up. Can anyone provide a solution to rectify this

I've been waiting for 30 minutes and my upload is still not completed. How can I resolve this issue? Click here to see the problem ...

Discovering the final step of a for loop when working with JavaScript objects

Currently, my data consists of: {12: Object, 13: Object, 14: Object} I need help figuring out how to detect the final iteration in the for loop below: for (var i in objs){ console.log(objs[i]); } Does anyone have any solutions? ...

Remove the 'name' attribute from the input tag within the URL

Is there a way to make the server update the URL format to localhost:3000/userinput instead of localhost:3000/?name=userinput when submitting a name? Any suggestions would be greatly appreciated. Thank you in advance. ExpressJs FILE <!DOCTYPE html> ...

The functionality of ng-model appears to be malfunctioning

I'm currently developing a MEAN Stack web application and I'm incorporating a 2D array in one of my models. Here's the schema for that specific field: alerts: [{ name: String, time: Number}] Now I'm trying to access this data in my U ...

Resource loading on hold until promise is resolved

Within one of my AngularJS controllers, I have the following line of code: api.tickets.query() The api module includes the following: angular.module('myapp.api', [ 'ngResource' ]) .factory('api', function($resource, appl ...

Is it possible to eliminate the port number in Angular 7?

Currently, I am utilizing Angular in conjunction with an ASP.Net Web application. One interesting observation I've made is that when I use ng build, the app builds and runs on a URL without any port number. However, if I run the app using ng serve, it ...

Display the button only if the specified condition aligns with the input data

I am working on a project where I have an input text field that retrieves data from a database using a combination of JavaScript and PHP. get.html is responsible for fetching the data through JavaScript. function showUser(str) { if (str == "") { ...

managing jquery AJAX requests recursively, signaling completion to the browser

I have a situation where I need to continuously fetch data from an endpoint using a next token if there are more items available. The code snippet below illustrates how I'm currently fetching the data: function get_all_entities(campaign_id, page){ ...

In my Vue project, I am required to extract only the numerical value from a select option text and disregard the rest of the text

Currently, I am in the process of learning Vue and have taken on the task of creating a basic tax calculator. The challenge is to display the result in real-time without requiring a "show total value" button. Everything seems to be functioning well except ...