Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Hcaptcha.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ export type HcaptchaProps = {
* The callback function that runs after receiving a response, error, or when user cancels.
*/
onMessage: (event: CustomWebViewMessageEvent) => void;
/**
* Runs after the hCaptcha API loads.
*/
onLoad?: () => void;
/**
* Runs when hCaptcha is ready to execute.
*/
onReady?: () => void;
/**
* The size of the checkbox.
*/
Expand Down
105 changes: 79 additions & 26 deletions Hcaptcha.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import hCaptchaLoaderInlineScript from '@hcaptcha/loader/inline';
import WebView from 'react-native-webview';
import { ActivityIndicator, Linking, Platform, StyleSheet, TouchableWithoutFeedback, View } from 'react-native';
import ReactNativeVersion from 'react-native/Libraries/Core/ReactNativeVersion';
Expand Down Expand Up @@ -26,6 +27,7 @@ const patchPostMessageJsCode = `(${String(function () {
window.ReactNativeWebView.postMessage = patchedPostMessage;
})})();`;

const HCAPTCHA_LOAD_EVENT = '__hcaptcha_load__';
const HCAPTCHA_READY_EVENT = '__hcaptcha_ready__';

const serializeForInlineScript = (value) =>
Expand Down Expand Up @@ -135,28 +137,45 @@ const buildVerifyData = ({
const buildVerifyInjectionScript = (payload, resetFirst = false) =>
`try { ${resetFirst ? 'reset(); ' : ''}setData(${serializeForInlineScript(payload)}); execute(); } catch (e) { window.ReactNativeWebView.postMessage((e && e.name) || 'error'); } true;`;

const buildHcaptchaApiUrl = (jsSrc, siteKey, hl, theme, host, sentry, endpoint, assethost, imghost, reportapi, orientation) => {
var url = `${jsSrc || 'https://hcaptcha.com/1/api.js'}?render=explicit&onload=onloadCallback`;

let effectiveHost;
const getHcaptchaHost = (host, siteKey) => {
if (host) {
effectiveHost = encodeURIComponent(host);
return host;
} else if (siteKey) {
return `${siteKey}.react-native.hcaptcha.com`;
} else {
effectiveHost = (siteKey || 'missing-sitekey') + '.react-native.hcaptcha.com';
}

for (let [key, value] of Object.entries({ host: effectiveHost, hl, custom: typeof theme === 'object', sentry, endpoint, assethost, imghost, reportapi, orientation })) {
if (value) {
url += `&${key}=${encodeURIComponent(value)}`;
}
return 'missing-sitekey.react-native.hcaptcha.com';
}

return url;
};

const buildHcaptchaLoaderConfig = ({
scriptSource,
siteKey,
hl,
theme,
host,
sentry,
endpoint,
assethost,
imghost,
reportapi,
}) => ({
scriptSource,
render: 'explicit',
host: getHcaptchaHost(host, siteKey),
hl,
custom: typeof theme === 'object',
sentry: Boolean(sentry),
endpoint,
assethost,
imghost,
reportapi,
});

/**
*
* @param {*} onMessage: callback after receiving response, error, or when user cancels
* @param {function} onLoad: callback after the hCaptcha API loads
* @param {function} onReady: callback when hCaptcha is ready to execute
* @param {*} siteKey: your hCaptcha sitekey
* @param {string} size: The size of the widget, can be 'invisible', 'compact' or 'normal'. 'checkbox' is kept as a legacy alias for 'normal'. Default: 'invisible'
* @param {*} style: custom style
Expand Down Expand Up @@ -184,6 +203,8 @@ const buildHcaptchaApiUrl = (jsSrc, siteKey, hl, theme, host, sentry, endpoint,
*/
const Hcaptcha = ({
onMessage,
onLoad,
onReady,
size,
siteKey,
style,
Expand Down Expand Up @@ -217,9 +238,20 @@ const Hcaptcha = ({
const hasJourneyConsumerRef = useRef(false);
const normalizedTheme = useMemo(() => normalizeTheme(theme), [theme]);
const normalizedSize = useMemo(() => normalizeSize(size), [size]);
const apiUrl = useMemo(
() => buildHcaptchaApiUrl(jsSrc, siteKey, languageCode, normalizedTheme, host, sentry, endpoint, assethost, imghost, reportapi, orientation),
[jsSrc, siteKey, languageCode, normalizedTheme, host, sentry, endpoint, assethost, imghost, reportapi, orientation]
const loaderConfig = useMemo(
() => buildHcaptchaLoaderConfig({
scriptSource: jsSrc,
siteKey,
hl: languageCode,
theme: normalizedTheme,
host,
sentry,
endpoint,
assethost,
imghost,
reportapi,
}),
[jsSrc, siteKey, languageCode, normalizedTheme, host, sentry, endpoint, assethost, imghost, reportapi]
);

const debugInfo = useMemo(
Expand All @@ -229,17 +261,18 @@ const Hcaptcha = ({

const serializedWebViewConfig = useMemo(
() => serializeForInlineScript({
apiUrl,
loaderConfig,
backgroundColor: backgroundColor ?? '',
debugInfo,
phoneNumber: phoneNumber ?? null,
phonePrefix: phonePrefix ?? null,
orientation: orientation ?? null,
rqdata: rqdata ?? null,
siteKey: siteKey || '',
size: normalizedSize,
theme: normalizedTheme,
}),
[apiUrl, backgroundColor, debugInfo, normalizedSize, normalizedTheme, phoneNumber, phonePrefix, rqdata, siteKey]
[loaderConfig, backgroundColor, debugInfo, normalizedSize, normalizedTheme, orientation, phoneNumber, phonePrefix, rqdata, siteKey]
);

const generateTheWebViewContent = useMemo(
Expand All @@ -254,13 +287,19 @@ const Hcaptcha = ({
var hcaptchaConfig = ${serializedWebViewConfig};
Object.entries(hcaptchaConfig.debugInfo || {}).forEach(function (entry) { window[entry[0]] = entry[1] });
</script>
<script type="text/javascript">
${hCaptchaLoaderInlineScript}
</script>
<script type="text/javascript">
var loadApiScript = function() {
var script = document.createElement('script');
script.async = true;
script.defer = true;
script.src = hcaptchaConfig.apiUrl;
document.head.appendChild(script);
if (typeof window.hCaptchaLoader !== 'function') {
window.ReactNativeWebView.postMessage('error');
return;
}

window.hCaptchaLoader(hcaptchaConfig.loaderConfig).then(onloadCallback).catch(function(error) {
window.ReactNativeWebView.postMessage((error && error.message) || (error && error.name) || 'error');
});
};
var hcaptchaWidgetId = null;
var setData = function(data) {
Expand All @@ -273,9 +312,10 @@ const Hcaptcha = ({
hcaptcha.reset(hcaptchaWidgetId);
};
var onloadCallback = function() {
window.ReactNativeWebView.postMessage("${HCAPTCHA_LOAD_EVENT}");
try {
console.log("challenge onload starting");
hcaptchaWidgetId = hcaptcha.render("hcaptcha-container", getRenderConfig(hcaptchaConfig.siteKey, hcaptchaConfig.theme, hcaptchaConfig.size));
hcaptchaWidgetId = hcaptcha.render("hcaptcha-container", getRenderConfig(hcaptchaConfig.siteKey, hcaptchaConfig.theme, hcaptchaConfig.size, hcaptchaConfig.orientation));
window.ReactNativeWebView.postMessage("${HCAPTCHA_READY_EVENT}");
// have loaded by this point; render is sync.
console.log("challenge render complete");
Expand All @@ -301,7 +341,7 @@ const Hcaptcha = ({
console.warn("challenge error callback fired");
window.ReactNativeWebView.postMessage(error);
};
const getRenderConfig = function(siteKey, theme, size) {
const getRenderConfig = function(siteKey, theme, size, orientation) {
var config = {
sitekey: siteKey,
size: size,
Expand All @@ -315,6 +355,9 @@ const Hcaptcha = ({
if (theme) {
config.theme = theme;
}
if (orientation) {
config.orientation = orientation;
}
return config;
};
loadApiScript();
Expand Down Expand Up @@ -407,8 +450,18 @@ const Hcaptcha = ({
}}
mixedContentMode={'always'}
onMessage={(e) => {
if (e.nativeEvent.data === HCAPTCHA_LOAD_EVENT) {
if (onLoad) {
onLoad();
}
return;
}

if (e.nativeEvent.data === HCAPTCHA_READY_EVENT) {
injectVerifyData();
if (onReady) {
onReady();
}
return;
}

Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ Otherwise, you should pass in the preferred device locale, e.g. fetched from `ge
- The UI defaults to the "invisible" mode of the JS SDK, i.e. no checkbox is displayed.
- If you need to test displaying the challenge modal, set your sitekey to "Always Challenge" mode in the hCaptcha dashboard.
- You can `import { Hcaptcha } from '@hcaptcha/react-native-hcaptcha';` to customize the UI yourself.
- hCaptcha loading is restricted to a 15-second timeout; an `error` will be sent via `onMessage` if it fails to load due to network issues.
- The legacy 15-second loading timeout event is deprecated and should not be treated as a terminal failure. Do not hide or unmount hCaptcha when it occurs. Use `onReady` to detect successful initialization and `script-error` from `onMessage` to detect failure after loader retries are exhausted.

## Journey Capture Caveats

Expand Down Expand Up @@ -344,6 +344,8 @@ For new code, prefer:
| siteKey _(required)_ | string | The hCaptcha siteKey |
| size | string | The size of the widget, can be 'invisible', 'compact' or 'normal'. `checkbox` is also accepted as a legacy alias for `normal`. Default: 'invisible' |
| onMessage | Function (see [here](https://github.com/react-native-webview/react-native-webview/blob/master/src/WebViewTypes.ts#L299)) | Required. Runs after receiving a response, error, or when user cancels. |
| onLoad | Function | Runs after the hCaptcha API loads. |
| onReady | Function | Runs when hCaptcha is ready to execute. |
| languageCode | string | Default language for hCaptcha; overrides phone defaults. A complete list of supported languages and their codes can be found [here](https://docs.hcaptcha.com/languages/) |
| showLoading | boolean | Whether to show a loading indicator while the hCaptcha web content loads |
| closableLoading | boolean | Allow user to cancel hcaptcha during loading by touch loader overlay |
Expand Down
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ class ConfirmHcaptcha extends PureComponent {
languageCode,
orientation,
onMessage,
onLoad,
onReady,
showLoading,
closableLoading,
loadingIndicatorColor,
Expand Down Expand Up @@ -98,6 +100,8 @@ class ConfirmHcaptcha extends PureComponent {
size={size}
siteKey={siteKey}
onMessage={onMessage}
onLoad={onLoad}
onReady={onReady}
languageCode={languageCode}
showLoading={showLoading}
closableLoading={closableLoading}
Expand Down Expand Up @@ -207,6 +211,8 @@ ConfirmHcaptcha.propTypes = {
passiveSiteKey: PropTypes.bool,
baseUrl: PropTypes.string,
onMessage: PropTypes.func.isRequired,
onLoad: PropTypes.func,
onReady: PropTypes.func,
languageCode: PropTypes.string,
orientation: PropTypes.string,
backgroundColor: PropTypes.string,
Expand Down Expand Up @@ -237,6 +243,8 @@ ConfirmHcaptcha.propTypes = {
ConfirmHcaptcha.defaultProps = {
size: 'invisible',
passiveSiteKey: false,
onLoad: undefined,
onReady: undefined,
showLoading: false,
closableLoading: false,
orientation: 'portrait',
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@
"url": "https://github.com/hCaptcha/react-native-hcaptcha/issues"
},
"homepage": "https://github.com/hCaptcha/react-native-hcaptcha#readme",
"dependencies": {
"@hcaptcha/loader": "github:hCaptcha/hcaptcha-loader#e96798848192e64012e156161a9251c4e3e97b94"
},
"peerDependencies": {
"react": "*",
"react-native": "*",
Expand Down
Loading