Using reCAPTCHA in Lightning Components Salesforce

Before we start with we need to create a site key in the reCAPTCHA admin site.
This site key will allow to the Google API for reCAPTCHA to validate our site.
To get a valid site key you need to have a Google account.
Then, once login, navigate to this site.

Set the domain,( click on VF page and Get Domain  From URL, in our case, “bv007-dev-ed–c.visualforce.com“,).

And select the reCAPTCHA V2 checkbox.

You can see the needed configuration in this image:-

VF Page:- "reCaptachaVFPage"
<apex:page showHeader="false" >
<html>
<head>
<title>reCAPTCHA demo: Explicit render after an onload callback</title>
<script type="text/javascript">
var verifyCallback = function(response) {
parent.postMessage("Unlock", "https://bv007-dev-ed.lightning.force.com"); // Here, https://bv007-dev-ed.lightning.force.com is Lightning URL.
};
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : '6LfoXLEUAAAAAJh6uaq8CvfcNahStQ18bGjpx6RG', // SiteKey get from google.com
'callback' : verifyCallback,
});
};
</script>
</head>
<body>
<form action="?" method="POST">
<div id="html_element"></div>
<br/>
<input type="submit" value="Submit" style="display:none"/>
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async="" defer="">
</script>
</body>
</html>
</apex:page>
Lightning Component:- sfdc_reCaptchaComponent
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<!--iframe src="/apex/reCaptachaVFPage" height="74px" style="border:0px"/-->

<iframe aura:id="vfFrame"
class="slds-m-top--medium"
src="/apex/reCaptachaVFPage"
scrolling="no" frameborder="0" height="500px" width="350px" allowtransparency="true"/>
<br/>
<lightning:button aura:id="myButton" label="Submit" onclick="{!c.doSubmit}" disabled="true" />
</aura:component>
Controller.js
({
doInit: function (cmp, evt, helper){
debugger;
let vfOrigin = "https://bv007-dev-ed--c.visualforce.com"; // VF Page URL
window.addEventListener("message", function(event) {
debugger;
alert("1 "+ event.data);
alert("2 "+ event.origin);
console.log('<<<<<event.data>>>>>'+event.data);
console.log('>>>>>event.origin>>>>'+event.origin);
if (event.origin !== vfOrigin) {
// Not the expected origin: Reject the message!
return;
}
if (event.data==="Unlock"){
let myButton = cmp.find("myButton");
myButton.set('v.disabled', false);
}
}, false);
},
doSubmit: function (cmp, evt, helper){
debugger;
//var message=10;
alert("Do Submit");
}

})
LightningApplication: reCaptchaApp
<aura:application >
<c:sfdccode_reCaptchaComponent></c:sfdccode_reCaptchaComponent>
</aura:application>

OutPut:-

Leave a Reply