[SalesForce] Google Recaptcha V3 Implementation in Lightning Web Component

I have requirement to add Recaptcha in Lightning Web Component component. I have used V3 of google recaptacha. I have added https://www.google.com/recaptcha/api.js url in static resource and referenced in LWC component.

On running this is showing

"Access to XMLHttpRequest at 'https://www.gstatic.com/recaptcha/api2/v1550471573786/recaptcha__en.js' from origin 'https://******–*****–livepreview.cs77.force.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I have added url in CORS,CSP sites and Remote site setting. Can any one help in this issue.

Best Answer

I have a solution that you can try.

Upload a static resource: recaptcha2.html

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" onsubmit="return validateForm()" method="POST">
      <div class="g-recaptcha" data-sitekey="6LdIAZgUAAAAAFX4gX_8CQrVXT-5kPka0w_i2bnY"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>

    <script type="text/javascript">
        function validateForm(){

            if(grecaptcha.getResponse().length == 0){
                alert('Please click the reCAPTCHA checkbox');
                parent.postMessage("captcha failed", location.origin);
                return false;
            }
            parent.postMessage("captcha success", location.origin);
            return true;
        }
    </script>
  </body>
</html>

You will need to create a resource file called: recaptcha2.resource-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
    <cacheControl>Private</cacheControl>
    <contentType>text/html</contentType>
</StaticResource>

Make an LWC component: captcha.html

<template>
    <iframe src={navigateTo} name="captchaFrame" onload={captchaLoaded} width="350" height="500" style="border:1px solid red"></iframe>
</template>

and the JavaScript: captcha.js

import { LightningElement, track } from 'lwc';
import pageUrl from '@salesforce/resourceUrl/recaptcha2';

export default class GoogleCapatcha extends LightningElement {
    @track navigateTo;
    captchaWindow = null;

    constructor(){
        super();

        this.navigateTo = pageUrl;

        window.addEventListener("message", this.listenForMessage);
    }

    captchaLoaded(evt){
        var e = evt;
        console.log(e.target.getAttribute('src') + ' loaded');
        if(e.target.getAttribute('src') == pageUrl){
            // You know that your captcha is loaded
        } 
    }

    listenForMessage(message){
        console.log(message);
    }
}

I hadn't used a captcha prior, when registering the domain I didn't realize that I should leave off the https://.

Related Topic