diff --git a/.eslintignore b/.eslintignore
index 4db3705..89b157f 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -1 +1,10 @@
+node_modules/
+# Generated web example bundle
+dist/
+# Generated E2E host app
__e2e__/host/
+# Reassure output
+.reassure/
+output/
+# Jest coverage output
+coverage/
diff --git a/.eslintrc.js b/.eslintrc.js
index 187894b..0bc60c7 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -1,4 +1,15 @@
module.exports = {
root: true,
extends: '@react-native',
+ overrides: [
+ {
+ // The react-native-web suite lives outside __tests__ so the native Jest project
+ // does not pick it up; ESLint still needs the Jest globals here.
+ files: ['**/__tests_web__/**/*.js'],
+ env: {
+ jest: true,
+ 'jest/globals': true,
+ },
+ },
+ ],
};
diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml
index 1356bb1..846f8e1 100644
--- a/.github/workflows/tests.yaml
+++ b/.github/workflows/tests.yaml
@@ -24,6 +24,7 @@ jobs:
- run: npm install
- run: npm test
- run: npm run lint
+ - run: npm run build:web
- if: github.ref == 'refs/heads/master' && github.event_name == 'push'
run: npm run perf:baseline
- if: github.ref == 'refs/heads/master' && github.event_name == 'push'
diff --git a/.gitignore b/.gitignore
index 0be1efb..d6a32aa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,3 +9,9 @@ output/
# Generated E2E host app
__e2e__/host/
+
+# Web example build output
+dist/
+
+# Jest coverage output
+coverage/
diff --git a/Example.Web.js b/Example.Web.js
new file mode 100644
index 0000000..ba10308
--- /dev/null
+++ b/Example.Web.js
@@ -0,0 +1,97 @@
+import React, { useRef, useState } from 'react';
+import { AppRegistry, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
+import ConfirmHcaptcha from './index';
+
+// demo sitekey
+// Swap in hCaptcha's always-pass test key '10000000-ffff-ffff-ffff-000000000001'
+// to exercise the token path without solving a visual challenge.
+const siteKey = '00000000-0000-0000-0000-000000000000';
+const baseUrl = 'https://hcaptcha.com';
+
+const App = () => {
+ const [code, setCode] = useState(null);
+ const captchaForm = useRef(null);
+
+ const onMessage = event => {
+ if (event && event.nativeEvent.data) {
+ if (event.nativeEvent.data === 'open') {
+ console.log('Visual challenge opened');
+ } else if (event.success) {
+ setCode(event.nativeEvent.data);
+ captchaForm.current.hide();
+ event.markUsed();
+ console.log('Verified code from hCaptcha', event.nativeEvent.data);
+ } else if (event.nativeEvent.data === 'challenge-expired') {
+ event.reset();
+ console.log('Visual challenge expired, reset...', event.nativeEvent.data);
+ } else /* other errors */ {
+ setCode(event.nativeEvent.data);
+ captchaForm.current.hide();
+ console.log('Verification failed', event.nativeEvent.data);
+ }
+ }
+ };
+
+ return (
+
+ hCaptcha · React Native Web
+
+ {
+ captchaForm.current.show();
+ }}
+ testID="launch-button">
+ Click to launch
+
+ {code && (
+
+ {'passcode or status: '}
+
+ {code}
+
+
+ )}
+
+ );
+};
+
+const styles = StyleSheet.create({
+ container: {
+ flex: 1,
+ justifyContent: 'center',
+ backgroundColor: '#ecf0f1',
+ padding: 8,
+ },
+ heading: {
+ fontSize: 22,
+ fontWeight: 'bold',
+ textAlign: 'center',
+ },
+ paragraph: {
+ margin: 24,
+ fontSize: 18,
+ fontWeight: 'bold',
+ textAlign: 'center',
+ },
+ codeContainer: {
+ alignSelf: 'center',
+ },
+ codeText: {
+ color: 'darkviolet',
+ fontSize: 10,
+ fontWeight: 'bold',
+ },
+});
+
+AppRegistry.registerComponent('HcaptchaWebExample', () => App);
+AppRegistry.runApplication('HcaptchaWebExample', {
+ rootTag: document.getElementById('root'),
+});
+
+export default App;
diff --git a/Hcaptcha.js b/Hcaptcha.js
index 528a359..bb92b43 100644
--- a/Hcaptcha.js
+++ b/Hcaptcha.js
@@ -1,11 +1,20 @@
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, 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';
+import { ActivityIndicator, Linking, StyleSheet, TouchableWithoutFeedback, View } from 'react-native';
-import md5 from './md5';
-import hcaptchaPackage from './package.json';
+import {
+ buildDebugInfo,
+ buildHcaptchaLoaderConfig,
+ buildVerifyData,
+ HCAPTCHA_READY_EVENT,
+ LOADING_TIMEOUT,
+ normalizeSize,
+ normalizeTheme,
+ serializeForInlineScript,
+ TOKEN_MIN_LENGTH,
+ TOKEN_TIMEOUT,
+} from './hcaptchaShared';
import {
clearJourneyEvents,
disableJourneyConsumer,
@@ -27,153 +36,12 @@ const patchPostMessageJsCode = `(${String(function () {
window.ReactNativeWebView.postMessage = patchedPostMessage;
})})();`;
-const HCAPTCHA_READY_EVENT = '__hcaptcha_ready__';
const HCAPTCHA_REQUEST_EVENT = '__hcaptcha_request__:';
const HCAPTCHA_LOAD_ERROR_EVENT = '__hcaptcha_load_error__:';
-const serializeForInlineScript = (value) =>
- JSON.stringify(value)
- .replace(//g, '\\u003e')
- .replace(/&/g, '\\u0026')
- .replace(/\u2028/g, '\\u2028')
- .replace(/\u2029/g, '\\u2029');
-
-const normalizeTheme = (value) => {
- if (value == null) {
- return null;
- }
-
- if (typeof value === 'object') {
- return value;
- }
-
- if (typeof value === 'string') {
- try {
- return JSON.parse(value);
- } catch (_) {
- return value;
- }
- }
-
- return value;
-};
-
-const normalizeSize = (value) => {
- if (value == null) {
- return 'invisible';
- }
-
- return value === 'checkbox' ? 'normal' : value;
-};
-
-const getVersionPart = (value) => (
- typeof value === 'number' && Number.isFinite(value) && value >= 0 && value < 100
- ? value
- : null
-);
-
-const parseReactNativeVersion = (value) => {
- const candidate = value && typeof value === 'object' && value.version ? value.version : value;
- const major = getVersionPart(candidate?.major);
- const minor = getVersionPart(candidate?.minor);
- const patch = getVersionPart(candidate?.patch);
-
- if (major == null || minor == null || patch == null) {
- return null;
- }
-
- return { major, minor, patch };
-};
-
-const getReactNativeVersion = (value = Platform?.constants?.reactNativeVersion) =>
- parseReactNativeVersion(value) || parseReactNativeVersion(ReactNativeVersion?.version);
-
-const buildDebugInfo = (debug, reactNativeVersion = Platform?.constants?.reactNativeVersion) => {
- const result = { ...(debug || {}) };
-
- try {
- const version = getReactNativeVersion(reactNativeVersion);
- if (version) {
- result[`rnver_${version.major}_${version.minor}_${version.patch}`] = true;
- }
- result['dep_' + md5(Object.keys(global).join(''))] = true;
- result['sdk_' + hcaptchaPackage.version.toString().replace(/\./g, '_')] = true;
- } catch (e) {
- console.log(e);
- }
-
- return result;
-};
-
-const buildVerifyData = ({
- phoneNumber,
- phonePrefix,
- rqdata,
- userJourney,
- verifyParams,
-}) => {
- const normalizedVerifyParams = verifyParams || {};
- const data = {};
- const finalRqdata = normalizedVerifyParams.rqdata ?? rqdata ?? undefined;
- const finalPhonePrefix = normalizedVerifyParams.phonePrefix ?? phonePrefix ?? undefined;
- const finalPhoneNumber = normalizedVerifyParams.phoneNumber ?? phoneNumber ?? undefined;
-
- if (finalRqdata) {
- data.rqdata = finalRqdata;
- }
- if (finalPhonePrefix) {
- data.mfa_phoneprefix = finalPhonePrefix;
- }
- if (finalPhoneNumber) {
- data.mfa_phone = finalPhoneNumber;
- }
- if (Array.isArray(userJourney) && userJourney.length > 0) {
- data.userjourney = userJourney;
- }
-
- return data;
-};
-
const buildVerifyInjectionScript = (payload, resetFirst = false, requestId) =>
`try { ${resetFirst ? 'reset(); ' : ''}${requestId === undefined ? '' : `setRequest(${requestId}); `}setData(${serializeForInlineScript(payload)}); execute(); } catch (e) { window.ReactNativeWebView.postMessage((e && e.name) || 'error'); } true;`;
-const getHcaptchaHost = (host, siteKey) => {
- if (host) {
- return host;
- } else if (siteKey) {
- return `${siteKey}.react-native.hcaptcha.com`;
- } else {
- return 'missing-sitekey.react-native.hcaptcha.com';
- }
-};
-
-function buildHcaptchaLoaderConfig({
- scriptSource,
- siteKey,
- hl,
- theme,
- host,
- sentry,
- endpoint,
- assethost,
- imghost,
- reportapi,
-}) {
- return {
- scriptSource: scriptSource || 'https://hcaptcha.com/1/api.js',
- render: 'explicit',
- host: getHcaptchaHost(host, siteKey),
- hl,
- custom: typeof theme === 'object',
- sentry,
- endpoint,
- assethost,
- imghost,
- reportapi,
- };
-}
-
/**
*
* @param {*} onMessage: callback after receiving response, error, or when user cancels
@@ -234,8 +102,6 @@ const Hcaptcha = forwardRef(({
_onRequestChange,
_onTokenTimerChange,
}, ref) => {
- const tokenTimeout = 120000;
- const loadingTimeout = 15000;
const [isLoading, setIsLoading] = useState(true);
const [webViewGeneration, setWebViewGeneration] = useState(0);
const [destroyed, setDestroyed] = useState(false);
@@ -465,7 +331,7 @@ const Hcaptcha = forwardRef(({
onMessageRef.current({ nativeEvent: { data: 'error', description: 'loading timeout' }, success: false, reset });
}
}
- }, loadingTimeout);
+ }, LOADING_TIMEOUT);
}, [reset, setExecuteRequested]);
const documentKey = useMemo(() => JSON.stringify([serializedWebViewConfig, url, webViewGeneration, prewarm]), [serializedWebViewConfig, url, webViewGeneration, prewarm]);
@@ -730,7 +596,7 @@ const Hcaptcha = forwardRef(({
clearTimeout(loadingTimerRef.current);
isLoadingRef.current = false;
setIsLoading(false);
- } else if ((!prewarm || readyRef.current) && !requestError && e.nativeEvent.data.length > 35) {
+ } else if ((!prewarm || readyRef.current) && !requestError && e.nativeEvent.data.length > TOKEN_MIN_LENGTH) {
if (prewarm && !executeRequestedRef.current) {
return;
}
@@ -742,7 +608,7 @@ const Hcaptcha = forwardRef(({
const expiredTokenTimerId = setTimeout(() => {
_onTokenTimerChange?.(expiredTokenTimerId, false);
onMessageRef.current({ nativeEvent: { data: 'expired' }, success: false, reset });
- }, tokenTimeout);
+ }, TOKEN_TIMEOUT);
tokenTimerRef.current = expiredTokenTimerId;
_onTokenTimerChange?.(expiredTokenTimerId, true);
e.markUsed = () => {
diff --git a/Hcaptcha.web.js b/Hcaptcha.web.js
new file mode 100644
index 0000000..cba1d64
--- /dev/null
+++ b/Hcaptcha.web.js
@@ -0,0 +1,332 @@
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { hCaptchaLoader } from '@hcaptcha/loader';
+import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';
+
+import {
+ buildDebugInfo,
+ buildHcaptchaLoaderConfig,
+ buildRenderConfig,
+ buildVerifyData,
+ LOADING_TIMEOUT,
+ normalizeSize,
+ normalizeTheme,
+ TOKEN_MIN_LENGTH,
+ TOKEN_TIMEOUT,
+} from './hcaptchaShared';
+import {
+ clearJourneyEvents,
+ disableJourneyConsumer,
+ enableJourneyConsumer,
+ peekJourneyEvents,
+} from './journey';
+
+/**
+ * Web implementation of the hCaptcha component.
+ *
+ * On native the widget is isolated inside a WebView and the two sides talk over
+ * `postMessage` / `injectJavaScript`. On web the host page *is* a browser, so the
+ * widget is rendered straight into the document with `@hcaptcha/loader` — the same
+ * loader the native HTML uses — and the message channel collapses into direct calls.
+ *
+ * The `onMessage` contract is deliberately identical to the native one: every event is
+ * delivered as `{ nativeEvent: { data } }` carrying `success`, `reset` and, for tokens,
+ * `markUsed`. That keeps `index.js`, the public API and the type definitions unchanged.
+ */
+const Hcaptcha = ({
+ onMessage,
+ size,
+ siteKey,
+ style,
+ languageCode,
+ showLoading,
+ closableLoading,
+ loadingIndicatorColor,
+ theme,
+ rqdata,
+ sentry,
+ jsSrc,
+ endpoint,
+ reportapi,
+ assethost,
+ imghost,
+ host,
+ debug,
+ orientation,
+ phonePrefix,
+ phoneNumber,
+ userJourney,
+ verifyParams,
+ _journeyManagedExternally,
+}) => {
+ const [isLoading, setIsLoading] = useState(true);
+ const isLoadingRef = useRef(true);
+ const containerRef = useRef(null);
+ const widgetIdRef = useRef(null);
+ const hasRenderedRef = useRef(false);
+ // Bumped on every load and on unmount, so a loader promise from an earlier load or
+ // an unmounted instance settles into a no-op instead of reaching `onMessage`.
+ const loadGenerationRef = useRef(0);
+ const journeyEnabled = Boolean(userJourney);
+ // Read at execute time: a pending loader holds an old `applyVerifyData`, and the flag
+ // may have been turned off before it resolves.
+ const journeyEnabledRef = useRef(journeyEnabled);
+ journeyEnabledRef.current = journeyEnabled;
+ const hasJourneyConsumerRef = useRef(false);
+ // Declared up front: `emit` and the widget callbacks are mutually recursive with the
+ // loader, so both are reached through refs that are populated further down.
+ const emitRef = useRef(null);
+ const callbacksRef = useRef(null);
+
+ const normalizedTheme = useMemo(() => normalizeTheme(theme), [theme]);
+ const normalizedSize = useMemo(() => normalizeSize(size), [size]);
+
+ 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(() => buildDebugInfo(debug), [debug]);
+
+ // The native build exposes these as globals inside its WebView, where hCaptcha reads
+ // them. On web the widget runs in the host document, so they go on `window` instead.
+ useEffect(() => {
+ if (typeof window === 'undefined') {
+ return;
+ }
+
+ Object.entries(debugInfo || {}).forEach(([key, value]) => {
+ window[key] = value;
+ });
+ }, [debugInfo]);
+
+ // Latest verify inputs, read at execute time rather than captured at render time so
+ // journey events buffered after mount are still included.
+ const verifyInputsRef = useRef(null);
+ verifyInputsRef.current = { phoneNumber, phonePrefix, rqdata, verifyParams };
+
+ const onMessageRef = useRef(onMessage);
+ onMessageRef.current = onMessage;
+
+ const getApi = () => (typeof window === 'undefined' ? null : window.hcaptcha);
+
+ const applyVerifyData = useCallback((resetFirst = false) => {
+ const api = getApi();
+ const widgetId = widgetIdRef.current;
+
+ if (!api || widgetId == null) {
+ return;
+ }
+
+ const { phoneNumber: pn, phonePrefix: pp, rqdata: rq, verifyParams: vp } = verifyInputsRef.current;
+
+ try {
+ if (resetFirst) {
+ api.reset(widgetId);
+ }
+ api.setData(widgetId, buildVerifyData({
+ phoneNumber: pn,
+ phonePrefix: pp,
+ rqdata: rq,
+ userJourney: journeyEnabledRef.current ? peekJourneyEvents() : undefined,
+ verifyParams: vp,
+ }));
+ api.execute(widgetId);
+ } catch (e) {
+ emitRef.current((e && e.name) || 'error');
+ }
+ }, []);
+
+ const reset = useCallback(() => applyVerifyData(true), [applyVerifyData]);
+
+ const loadApiScript = useCallback(() => {
+ const generation = ++loadGenerationRef.current;
+ const isStale = () => generation !== loadGenerationRef.current;
+
+ hCaptchaLoader(loaderConfig)
+ .then(() => {
+ if (isStale()) {
+ return;
+ }
+
+ const api = getApi();
+ const container = containerRef.current;
+
+ if (!api || !container || hasRenderedRef.current) {
+ return;
+ }
+
+ try {
+ widgetIdRef.current = api.render(container, buildRenderConfig({
+ siteKey: siteKey || '',
+ theme: normalizedTheme,
+ size: normalizedSize,
+ orientation,
+ callbacks: callbacksRef.current,
+ }));
+ hasRenderedRef.current = true;
+ // Parity with native's ready event: a rendered widget is no longer loading,
+ // even if it has not emitted open/token/error yet.
+ isLoadingRef.current = false;
+ setIsLoading(false);
+ applyVerifyData();
+ } catch (e) {
+ emitRef.current((e && e.name) || 'error');
+ }
+ })
+ .catch((error) => {
+ if (isStale()) {
+ return;
+ }
+
+ emitRef.current((error && error.message) || (error && error.name) || 'error');
+ });
+ }, [loaderConfig, siteKey, normalizedTheme, normalizedSize, orientation, applyVerifyData]);
+
+ const retryApiLoad = useCallback(() => {
+ hasRenderedRef.current = false;
+ widgetIdRef.current = null;
+ loadApiScript();
+ }, [loadApiScript]);
+
+ /**
+ * Mirrors the native `onMessage` handler exactly: same loading-state side effect,
+ * same `reset` selection, same token detection, same expiry timer.
+ */
+ const emit = useCallback((data, description) => {
+ isLoadingRef.current = false;
+ setIsLoading(false);
+
+ const event = { nativeEvent: { data } };
+ if (description !== undefined) {
+ event.nativeEvent.description = description;
+ }
+
+ event.reset = data === 'script-error' ? retryApiLoad : reset;
+ event.success = true;
+
+ if (data === 'open') {
+ // No extra handling; parity with native.
+ } else if (typeof data === 'string' && data.length > TOKEN_MIN_LENGTH) {
+ const expiredTokenTimerId = setTimeout(
+ () => onMessageRef.current({ nativeEvent: { data: 'expired' }, success: false, reset }),
+ TOKEN_TIMEOUT
+ );
+ event.markUsed = () => clearTimeout(expiredTokenTimerId);
+ if (journeyEnabled) {
+ clearJourneyEvents();
+ }
+ } else /* error */ {
+ event.success = false;
+ }
+
+ onMessageRef.current(event);
+ }, [journeyEnabled, reset, retryApiLoad]);
+
+ emitRef.current = emit;
+
+ callbacksRef.current = {
+ onData: (response) => emitRef.current(response),
+ onCancel: () => emitRef.current('challenge-closed'),
+ onOpen: () => emitRef.current('open'),
+ onDataExpired: (error) => emitRef.current(error || 'expired'),
+ onChalExpired: (error) => emitRef.current(error || 'challenge-expired'),
+ onDataError: (error) => emitRef.current(error || 'error'),
+ };
+
+ useEffect(() => {
+ if (_journeyManagedExternally || !journeyEnabled || hasJourneyConsumerRef.current) {
+ return undefined;
+ }
+
+ enableJourneyConsumer();
+ hasJourneyConsumerRef.current = true;
+
+ return () => {
+ if (hasJourneyConsumerRef.current) {
+ disableJourneyConsumer();
+ hasJourneyConsumerRef.current = false;
+ }
+ };
+ }, [_journeyManagedExternally, journeyEnabled]);
+
+ useEffect(() => {
+ const timeoutId = setTimeout(() => {
+ if (isLoadingRef.current) {
+ onMessageRef.current({ nativeEvent: { data: 'error', description: 'loading timeout' } });
+ }
+ }, LOADING_TIMEOUT);
+
+ return () => clearTimeout(timeoutId);
+ }, []);
+
+ useEffect(() => {
+ loadApiScript();
+
+ return () => {
+ const api = getApi();
+ const widgetId = widgetIdRef.current;
+
+ if (api && widgetId != null && typeof api.remove === 'function') {
+ try {
+ api.remove(widgetId);
+ } catch (e) {
+ // The widget may already be gone; nothing actionable here.
+ }
+ }
+
+ loadGenerationRef.current += 1;
+ widgetIdRef.current = null;
+ hasRenderedRef.current = false;
+ };
+ // Re-running on every config change would tear down an in-flight challenge, so the
+ // widget is created once per mount — matching the native WebView, which is also only
+ // built from the initial props.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const renderLoading = () => (
+ closableLoading && onMessageRef.current({ nativeEvent: { data: 'cancel' } })}
+ style={styles.loadingOverlay}>
+
+
+ );
+
+ return (
+
+
+ {showLoading && isLoading && renderLoading()}
+
+ );
+};
+
+const styles = StyleSheet.create({
+ container: {
+ flex: 1,
+ },
+ loadingOverlay: {
+ ...StyleSheet.absoluteFillObject,
+ justifyContent: 'center',
+ },
+ widget: {
+ alignItems: 'center',
+ backgroundColor: 'transparent',
+ flex: 1,
+ justifyContent: 'center',
+ width: '100%',
+ },
+});
+
+export default Hcaptcha;
+export { buildDebugInfo, buildVerifyData, HCAPTCHA_READY_EVENT } from './hcaptchaShared';
diff --git a/README.md b/README.md
index 4d53c8e..6990382 100644
--- a/README.md
+++ b/README.md
@@ -78,7 +78,7 @@ export default function Example() {
### Prewarming a multi-step flow
-Set `prewarm` to load the WebView and SDK on mount without fetching a token. It defaults to `false`, preserving the existing mount-on-`show()` behavior.
+Set `prewarm` to load the WebView and SDK on mount without fetching a token. It defaults to `false`, preserving the existing mount-on-`show()` behavior. Prewarming is native-only; it is [ignored on web](#react-native-web).
Mount `ConfirmHcaptcha` once at the app root, after your navigation/content, inside a full-screen `View`. Keep it mounted across screens. Call `captchaRef.current.execute()` when screen 2 loads; `show()` is equivalent. Calls made before SDK readiness are queued. `hide()` cancels pending verification and keeps the WebView warm for reuse.
@@ -293,9 +293,70 @@ The SDK automatically retries loading `api.js` after transient failures. Active
With `prewarm`, a 15-second loading timeout during an active request cancels that request and reports `loading timeout`; call `execute()` or `event.reset()` to retry. Idle preload failures and timeouts do not notify the app. Their failure state is retained so the next `execute()` retries; a timed-out document is recreated. Initialization can still finish in the background without fetching a token. Without `prewarm`, initialization and the pending verification continue after the timeout, preserving existing behavior.
+## React Native Web
+
+The library ships a web build, so the same `ConfirmHcaptcha` / `Hcaptcha` code runs
+under [react-native-web](https://necolas.github.io/react-native-web/) with no changes
+to your app.
+
+### Install
+
+```bash
+npm install react-native-web react-dom
+```
+
+Both are optional peer dependencies — native-only apps do not need them. Alias
+`react-native` to `react-native-web` in your bundler, exactly as react-native-web
+requires. No WebView shim, `Modal` stub or animation stub is needed: react-native-web
+provides those components, and the web build renders hCaptcha directly.
+
+### How it differs from native
+
+On native the widget is isolated inside a `WebView` and the two sides talk over
+`postMessage` / `injectJavaScript`. On web the host page is already a browser, so
+`Hcaptcha.web.js` loads `api.js` with [`@hcaptcha/loader`](https://github.com/hCaptcha/hcaptcha-loader)
+and renders the widget straight into the document.
+
+The public API is unchanged. `onMessage` receives the same
+`{ nativeEvent: { data } }` events with the same `success`, `reset` and `markUsed`
+fields, and `size`, `theme`, `rqdata`, `verifyParams`, MFA phone props, User Journeys,
+the 15-second loading timeout and the 120-second token expiry all behave as documented
+above.
+
+Four behaviours necessarily differ:
+
+| Prop / behaviour | On web |
+| --- | --- |
+| `backgroundColor` | Not applied to the page. On native it tints the WebView document body; on web that document is your app's own page, so the library leaves it alone. The `ConfirmHcaptcha` modal backdrop still uses it. |
+| `debug` | Debug markers are set on `window` rather than inside a WebView, because the widget now runs in the host document. |
+| `sms:` links | Handled by the browser and the hCaptcha widget directly; there is no WebView navigation to intercept, so no `sms-open-failed` event is emitted. |
+| `prewarm` | Ignored. Prewarming keeps a native WebView alive between `show()` calls; on web there is no WebView to keep, so `ConfirmHcaptcha` mounts on `show()` as if `prewarm` were `false`. The inline `Hcaptcha` export has no `execute()` / `reset()` / `destroy()` ref methods on web. |
+
+### Run the example
+
+```bash
+npm run web
+```
+
+Serves `Example.Web.js` on . To exercise the token path without
+solving a visual challenge, switch the example's `siteKey` to hCaptcha's always-pass
+test key `10000000-ffff-ffff-ffff-000000000001`.
+
+### Tests
+
+```bash
+npm run test:native # react-native suite
+npm run test:web # react-native-web suite (jsdom)
+npm test # both
+```
+
+The web suite stubs only the network fetch of `api.js` and the widget API it installs
+on `window`; the component itself renders for real.
+
## Dependencies
-1. [react-native-webview](https://github.com/react-native-community/react-native-webview)
+1. [react-native-webview](https://github.com/react-native-community/react-native-webview) (native only)
+2. [react-native-web](https://necolas.github.io/react-native-web/) and `react-dom` (web only, optional)
## Building on iOS
diff --git a/__mocks__/web.js b/__mocks__/web.js
new file mode 100644
index 0000000..a9422a8
--- /dev/null
+++ b/__mocks__/web.js
@@ -0,0 +1,106 @@
+// Web test setup.
+//
+// Deliberately narrow: the only thing stubbed is the *network* fetch of hCaptcha's
+// api.js and the widget API it installs on `window`. The component under test —
+// Hcaptcha.web.js and everything it renders — runs for real, so these tests exercise
+// the actual render path, loader wiring and event mapping.
+
+const createHcaptchaMock = () => {
+ const state = {
+ // Controls what the loader does on the next call. `hang` models an api.js request
+ // that never settles, which is what the loading timeout exists for. `defer` parks
+ // the request in `pendingLoad` so a test can settle it at a chosen moment.
+ loader: { shouldFail: false, error: null, hang: false, defer: false },
+ pendingLoad: null,
+ lastLoaderConfig: null,
+ loadCount: 0,
+ // Recorded widget interactions.
+ renderConfig: null,
+ renderTarget: null,
+ renderCount: 0,
+ renderThrows: false,
+ setDataCalls: [],
+ executeCount: 0,
+ resetCount: 0,
+ removeCount: 0,
+ widgetId: 'test-widget-id',
+ };
+
+ state.api = {
+ render: (target, config) => {
+ state.renderCount += 1;
+ state.renderTarget = target;
+ state.renderConfig = config;
+ if (state.renderThrows) {
+ const error = new Error('render failed');
+ error.name = 'RenderError';
+ throw error;
+ }
+ return state.widgetId;
+ },
+ setData: (widgetId, data) => {
+ state.setDataCalls.push({ widgetId, data });
+ },
+ execute: () => {
+ state.executeCount += 1;
+ },
+ reset: () => {
+ state.resetCount += 1;
+ },
+ remove: () => {
+ state.removeCount += 1;
+ },
+ };
+
+ // Invokes one of the callbacks the component handed to `hcaptcha.render`.
+ state.fire = (name, ...args) => {
+ const handler = state.renderConfig && state.renderConfig[name];
+ if (typeof handler !== 'function') {
+ throw new Error(`No hCaptcha callback registered for "${name}"`);
+ }
+ return handler(...args);
+ };
+
+ return state;
+};
+
+global.__hcaptcha = createHcaptchaMock();
+
+global.__resetHcaptchaMock = () => {
+ global.__hcaptcha = createHcaptchaMock();
+ delete global.hcaptcha;
+};
+
+jest.mock('@hcaptcha/loader', () => ({
+ hCaptchaLoader: (config) => {
+ const state = global.__hcaptcha;
+ state.lastLoaderConfig = config;
+ state.loadCount += 1;
+
+ if (state.loader.hang) {
+ return new Promise(() => {});
+ }
+
+ if (state.loader.defer) {
+ return new Promise((resolve, reject) => {
+ state.pendingLoad = {
+ resolve: () => {
+ global.hcaptcha = state.api;
+ resolve(global.hcaptcha);
+ },
+ reject,
+ };
+ });
+ }
+
+ if (state.loader.shouldFail) {
+ return Promise.reject(state.loader.error || new Error('script-error'));
+ }
+
+ // `global` is `window` under jsdom; a jest.mock factory may not close over `window`.
+ global.hcaptcha = state.api;
+ return Promise.resolve(global.hcaptcha);
+ },
+}));
+
+jest.mock('../md5', () => () => 'mocked-md5');
diff --git a/__scripts__/generate-example.js b/__scripts__/generate-example.js
index 633797d..e9e5ad8 100644
--- a/__scripts__/generate-example.js
+++ b/__scripts__/generate-example.js
@@ -162,6 +162,16 @@ function main({ cliName, projectRelativeProjectPath, projectName, projectTemplat
const destLibDir = path.join(projectPath, 'react-native-hcaptcha');
const excludes = ['__e2e__/host', '__tests__', '__mocks__', 'node_modules', '.git', 'output', '.reassure'].map(e => `--exclude=${e}`).join(' ');
execSync(`rsync -a ${excludes} ${libRoot}/ ${destLibDir}/`, { stdio: 'inherit' });
+ // npm installs a local directory dependency's devDependencies too, which a registry
+ // install never does. Unpinned ones (react-dom, react-test-renderer) resolve to the
+ // newest React and nest a second copy inside the library when the host pins an older
+ // one, so Metro bundles two Reacts and every hook call fails. `prepare` goes too: npm
+ // runs it for directory dependencies, and it calls husky, a devDependency.
+ const destPackagePath = path.join(destLibDir, 'package.json');
+ const destPackage = JSON.parse(fs.readFileSync(destPackagePath, 'utf8'));
+ delete destPackage.devDependencies;
+ delete destPackage.scripts.prepare;
+ fs.writeFileSync(destPackagePath, JSON.stringify(destPackage, null, 2) + '\n');
execSync('npm i --save file:./react-native-hcaptcha', packageManagerOptions);
execSync(`npm i --save-dev ${devPackages}`, packageManagerOptions);
execSync(`npm i --save ${peerPackages}`, packageManagerOptions);
diff --git a/__scripts__/run-e2e.js b/__scripts__/run-e2e.js
index da4ac25..1f0b3ec 100644
--- a/__scripts__/run-e2e.js
+++ b/__scripts__/run-e2e.js
@@ -23,7 +23,7 @@ fs.writeFileSync(
path.join(host, '__e2e__', 'ExampleAutopass.js'),
fs.readFileSync(path.join(root, 'Example.App.js'), 'utf8').replace('00000000-0000-0000-0000-000000000000', '10000000-ffff-ffff-ffff-000000000001')
);
-for (const file of ['Hcaptcha.js', 'index.js', 'md5.js', 'package.json', 'journey']) {
+for (const file of ['Hcaptcha.js', 'hcaptchaShared.js', 'reactNativeVersion.js', 'index.js', 'md5.js', 'package.json', 'journey']) {
fs.cpSync(path.join(root, file), path.join(host, 'react-native-hcaptcha', file), { recursive: true });
}
for (const file of fs.readdirSync(path.join(root, '__e2e__'))) {
diff --git a/__tests__/ConfirmHcaptcha.test.js b/__tests__/ConfirmHcaptcha.test.js
index bd6517d..fa9165a 100644
--- a/__tests__/ConfirmHcaptcha.test.js
+++ b/__tests__/ConfirmHcaptcha.test.js
@@ -308,7 +308,7 @@ describe('ConfirmHcaptcha', () => {
instance.show();
});
- const hiddenContainer = component.UNSAFE_getByProps({ pointerEvents: 'none' });
+ const hiddenContainer = component.getByTestId('confirm-hcaptcha-passive');
const safeAreaView = component.UNSAFE_getByType(SafeAreaView);
expect(component.UNSAFE_queryByType(Modal)).toBeNull();
@@ -318,6 +318,7 @@ describe('ConfirmHcaptcha', () => {
height: 1,
left: 0,
opacity: 0,
+ pointerEvents: 'none',
position: 'absolute',
top: 0,
width: 1,
diff --git a/__tests__/__snapshots__/ConfirmHcaptcha.test.js.snap b/__tests__/__snapshots__/ConfirmHcaptcha.test.js.snap
index ca1e5bc..16bfbc7 100644
--- a/__tests__/__snapshots__/ConfirmHcaptcha.test.js.snap
+++ b/__tests__/__snapshots__/ConfirmHcaptcha.test.js.snap
@@ -26,9 +26,20 @@ exports[`ConfirmHcaptcha renders ConfirmHcaptcha with minimum props after show()
"selected": undefined,
}
}
+ accessibilityValue={
+ {
+ "max": undefined,
+ "min": undefined,
+ "now": undefined,
+ "text": undefined,
+ }
+ }
accessible={true}
+ collapsable={false}
focusable={true}
+ onBlur={[Function]}
onClick={[Function]}
+ onFocus={[Function]}
onResponderGrant={[Function]}
onResponderMove={[Function]}
onResponderRelease={[Function]}
diff --git a/__tests__/__snapshots__/Hcaptcha.test.js.snap b/__tests__/__snapshots__/Hcaptcha.test.js.snap
index 026203e..295a4a9 100644
--- a/__tests__/__snapshots__/Hcaptcha.test.js.snap
+++ b/__tests__/__snapshots__/Hcaptcha.test.js.snap
@@ -49,7 +49,7 @@ exports[`Hcaptcha renders Hcaptcha with minimum props 1`] = `
+