Adding the SmartCaptcha widget
Adding the SmartCaptcha widget using the advanced method
You can control the widget loading process via the window.smartCaptcha object. However, in this guide, we will use the onloadFunction callback function:
-
Add the widget’s JS script to the user’s page by placing the following code inside the
<head>tag (or anywhere on the page):<script src="https://smartcaptcha.cloud.yandex.ru/captcha.js?render=onload&onload=onloadFunction" defer ></script> -
Add an empty container on the page. The system will use it to insert the widget:
<div id="<container_ID>"></div>Where
idis a random identifier. -
Add the callback function code on the page:
<script> function onloadFunction() { if (window.smartCaptcha) { const container = document.getElementById('<container_ID>'); const widgetId = window.smartCaptcha.render(container, { sitekey: '<client_key>', hl: '<language>', }); } } </script>Where:
<container_ID>: ID that was generated at the previous step.sitekey: Client-side key.hl: Language used for the widget and the challenge.
Consider adding an existence check for the
window.smartCaptchaobject in the callback function. It will prevent errors caused by calling the function before the script has finished loading.Note
Upon loading, the widget adjusts its container height to
100px, which may cause an unwanted layout shift. To avoid the layout shift, set the container height to100pxprior to the widget being loaded.<div ... style="height: 100px"></div>
Adding a SmartCaptcha widget with on-demand loading
To add a widget with on-demand CAPTCHA loading, use the following approach:
window.onloadFunction = () => {
if (window.smartCaptcha) {
// Creating a CAPTCHA
}
}
function handleScriptLoadingError() {
// Error handling
}
const scriptElement = document.createElement('script');
scriptElement.src = 'https://smartcaptcha.cloud.yandex.ru/captcha.js?render=onload&onload=onloadFunction';
scriptElement.onerror = handleScriptLoadingError;
document.body.appendChild(scriptElement);