Adding the SmartCaptcha widget
Adding the SmartCaptcha widget via the advanced method
You control how the widget loads via the window.smartCaptcha
object. This guide uses the onloadFunction
callback function for this:
-
Add the JS script to the user page. Do it by placing the following code anywhere on the page, e.g., inside the
<head>
tag:<script src="https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadFunction" defer ></script>
-
Add to the page an empty container for the widget:
<div id="<container_ID>"></div>
Where
id
is a random ID. -
Add the code of the callback function to 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 generated at the previous step.sitekey
: Client-side key.hl
: Widget and task language.
Consider adding an existence check for the
window.smartCaptcha
object into the callback function code to avoid error should the function be called before the JS script has finished loading.Note
During the upload, the widget changes the height of its host container to
100px
. This might result in an undesirable layout shift on the page due to the height change. To avoid this shift, set the100px
container height before the widget is loaded.<div ... style="height: 100px"></div>
Adding the SmartCaptcha widget that loads whenever required
To add the widget and have your CAPTCHA load whenever required, 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.yandexcloud.net/captcha.js?render=onload&onload=onloadFunction';
scriptElement.onerror = handleScriptLoadingError;
document.body.appendChild(scriptElement);