Add a SmartCaptcha widget
Add a SmartCaptcha widget using the advanced method
You control how the widget loads using the window.smartCaptcha
object. The onloadFunction
callback function is used for this in the guide:
-
Add the JS script to the user page. To do this, place the following code anywhere on the page, for example, inside the
<head>
tag:<script src="https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadFunction" defer ></script>
-
Add an empty container where you want to install your widget, to the page:
<div id="<container_ID>"></div>
Where
--id
is an ad-hoc 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 challenge language.
Add a check for existence of the
window.smartCaptcha
object to avoid an error when the function is called before the JS script loading is complete.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>
Add a SmartCaptcha widget as required
To add a widget and load CAPTCHA as required, use the following approach:
window.onloadFunction = () => {
if (window.smartCaptcha) {
// Creating a CAPTCHA
}
}
function handleScriptLoadingError() {
// Handling errors
}
const scriptElement = document.createElement('script');
scriptElement.src = 'https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadFunction';
scriptElement.onerror = handleScriptLoadingError;
document.body.appendChild(scriptElement);