8

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.

2
4

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://.

9
  • How are you checking that captcha is verified? It is similar to VF page addition in LWC component. Mar 16 '19 at 19:06
  • Do you mean, how would I notify the parent component that the form submission was successful?
    – Kevin Hill
    Mar 16 '19 at 20:14
  • Yes. How to check that captcha is verified? Because in LWC window.addEventListener will create problem. we can't raise event from this function. Mar 17 '19 at 15:42
  • You can use postMessage to send an event to the parent window. Let me update the Answer. Although this is now a different question :)
    – Kevin Hill
    Mar 17 '19 at 19:16
  • @Dhanik Lal Sahni did this answer your question?
    – Kevin Hill
    Mar 26 '19 at 2:44
4

Not to self promote, but I would like to share some new solutions to consider that don't require a VisualForce iframe in this just published blog post: https://www.learncommunitycloud.com/s/article/Implementing-reCAPTCHA-in-Community-Cloud

For v3, you can leverage JavaScript Events and Lightning Community head markup such as:

<!--reCaptcha v3-->
<script>
    document.addEventListener('grecaptchaExecute', function(e) {
        grecaptcha.execute('reCAPTCHA_site_key', {action: e.detail.action}).then(function(token) {
            document.dispatchEvent(new CustomEvent('grecaptchaVerified', {'detail': {response: token, action:e.detail.action}}));
        });
    }); 
</script>
<script src='https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key'></script>

*Replace reCAPTCHA_site_key with your v3 site key in 2 places in the example above

0

For anyone that followed the instructions above but got the "invalid domain for site key " error, make sure you add "https://www.google.com" to remote site settings.

Also, your static resource 's cache control should be public as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.