### Install Arcaptcha React Library Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/README.md Install the Arcaptcha React library using npm or yarn. ```bash npm install arcaptcha-react # or yarn add arcaptcha-react ``` -------------------------------- ### Example Usage of script_loading_failed_callback Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Shows how to implement the `script_loading_failed_callback` to handle cases where all script loading attempts fail. Logs the failed URLs and error, then displays a user-friendly alert. ```typescript { console.error('All CAPTCHA script URLs failed:'); info.urls.forEach(url => { console.error(`- ${url}`); }); console.error(`Last error: ${info.error}`); // Show user-friendly error message alert('Unable to load security verification. Please try again later.'); }} /> ``` -------------------------------- ### Example Usage of url_failed_callback Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Demonstrates how to use the `url_failed_callback` prop to handle individual URL loading failures. Logs information about the failed URL and its attempt status. ```typescript { console.log(`URL failed: ${info.url}`); console.log(`Attempt ${info.attemptNumber} of ${info.totalAttempts}`); if (info.isLastAttempt) { console.log('All URLs failed to load'); } }} /> ``` -------------------------------- ### Example Usage of ArcaptchaExecuteResponse Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Shows how to handle the ArcaptchaExecuteResponse after calling the execute method. This includes extracting the token and site key, and sending the token to a backend for verification. ```typescript try { const response = await arcaptchaRef.current?.execute(); const token = response.arcaptcha_token; const siteKey = response.site_key; // Send token to backend for verification await backend.verifyToken(token); } catch (error) { console.error('Verification failed:', error); } ``` -------------------------------- ### Example Usage of ArcaptchaWidgetHandle Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Demonstrates how to use the ArcaptchaWidgetHandle obtained via a ref to interact with the Arcaptcha widget. Includes triggering challenges, resetting, and closing the modal. ```typescript const arcaptchaRef = useRef(null); // Trigger challenge const response = await arcaptchaRef.current?.execute(); console.log(response.arcaptcha_token); // Reset widget arcaptchaRef.current?.resetCaptcha(); // Close modal arcaptchaRef.current?.close(); ``` -------------------------------- ### Backend Token Verification Example Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Example of how to verify Arcaptcha tokens on your backend using Node.js and Express. This code demonstrates making a POST request to the Arcaptcha verification API. ```javascript app.post('/verify-arcaptcha', async (req, res) => { const token = req.body.token; try { const response = await fetch('https://api.arcaptcha.ir/verify', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `secret=${SECRET_KEY}&token=${token}` }); const result = await response.json(); if (result.success) { res.json({ verified: true }); } else { res.status(400).json({ verified: false, error: result.error }); } } catch (error) { res.status(500).json({ error: error.message }); } }); ``` -------------------------------- ### ArCaptcha Component State Example Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/README.md Illustrates the expected state structure for the ArCaptcha component, including the widget ID and container div ID. ```javascript { widget_id: string // Arcaptcha widget ID after rendering id: string // Unique container div ID } ``` -------------------------------- ### Complete Arcaptcha Error Handling Example Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/errors.md This example demonstrates how to use various callback functions provided by the Arcaptcha widget to handle different error scenarios and user feedback. It covers script loading failures, verification errors, token expirations, and challenge expirations. ```javascript import React, { useState, useRef } from 'react'; import { ArcaptchaWidget } from 'arcaptcha-react'; function FormWithCaptcha() { const arcaptchaRef = useRef(null); const [error, setError] = useState(null); const [status, setStatus] = useState('idle'); const handleUrlFailed = (info) => { console.warn( `CAPTCHA URL ${info.attemptNumber}/${info.totalAttempts} failed: ${info.url}` ); if (info.isLastAttempt) { setError('Unable to load CAPTCHA. Trying again...'); } }; const handleScriptLoadingFailed = (info) => { console.error('All CAPTCHA URLs failed:', info.urls); setError( 'Unable to load security verification. Please check your ' 'internet connection and try again.' ); setStatus('error'); }; const handleCaptchaError = () => { console.error('CAPTCHA verification error'); setError('Verification failed. Please try again.'); setStatus('error'); }; const handleCaptchaExpired = () => { console.warn('CAPTCHA token expired'); setError('Your verification has expired. Please verify again.'); setStatus('expired'); }; const handleChallengeExpired = () => { console.warn('CAPTCHA challenge expired'); setError('The challenge expired. Please try again.'); setStatus('error'); }; const handleChallengeBlocked = () => { console.error('CAPTCHA blocked'); setError( 'Too many failed attempts. Please try again later.' ); setStatus('blocked'); }; const handleSubmit = async (e) => { e.preventDefault(); try { setStatus('verifying'); const response = await arcaptchaRef.current?.execute(); if (response?.arcaptcha_token) { // Send to backend const result = await fetch('/api/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: response.arcaptcha_token }) }); if (result.ok) { setStatus('success'); setError(null); } else { setError('Backend verification failed. Please try again.'); setStatus('error'); } } } catch (err) { console.error('Submit error:', err); setError('An unexpected error occurred. Please try again.'); setStatus('error'); } }; return (
{error &&
{error}
} ); } export default FormWithCaptcha; ``` -------------------------------- ### With URL Failure Monitoring Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/api-reference/ArcaptchaWidget.md Configure the ArcaptchaWidget to monitor URL loading failures and provide feedback through callbacks. This example demonstrates how to track individual URL issues and handle a complete script loading failure. Replace 'YOUR_SITE_KEY' with your actual site key. ```javascript import React, { useRef } from 'react'; import { ArcaptchaWidget } from 'arcaptcha-react'; export default function RobustWidget() { const arcaptchaRef = useRef(null); const [loadingIssues, setLoadingIssues] = React.useState([]); const handleUrlFailure = (info) => { setLoadingIssues(prev => [...prev, { url: info.url, attempt: `${info.attemptNumber}/${info.totalAttempts}`, error: info.error }]); }; const handleScriptLoadingFailed = (info) => { console.error('All CAPTCHA URLs failed'); console.error('Last error:', info.error); alert('Unable to load CAPTCHA. Please check your internet connection.'); }; return (
{loadingIssues.length > 0 && (

Encountered loading issues:

    {loadingIssues.map((issue, idx) => (
  • {issue.url} (Attempt {issue.attempt}): {issue.error}
  • ))}
)}
); } ``` -------------------------------- ### With All Callbacks Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/api-reference/ArcaptchaWidget.md Demonstrates the usage of all available callbacks for the ArcaptchaWidget, providing granular control and feedback on various widget events. Replace 'YOUR_SITE_KEY' with your actual site key. ```javascript import React, { Component, createRef } from 'react'; import { ArcaptchaWidget } from 'arcaptcha-react'; class FullCallbackExample extends Component { arcaptchaRef = createRef(); onSuccess = (token) => { console.log('✓ Verification successful:', token); }; onRendered = () => { console.log('✓ Widget rendered'); }; onOpened = () => { console.log('✓ Challenge opened'); }; onClosed = () => { console.log('✓ Challenge closed'); }; onError = () => { console.log('✗ Error occurred'); }; onReset = () => { console.log('↻ Widget reset'); }; onExpired = () => { console.log('✗ Token expired'); }; onChallengExpired = () => { console.log('✗ Challenge expired'); }; render() { return ( ); } } export default FullCallbackExample; ``` -------------------------------- ### ArcaptchaWidget with All Callbacks Configured Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Demonstrates configuring all available callback functions for various events, such as success, rendering, challenge status, and errors. ```javascript console.log('Success:', token)} rendered_callback={() => console.log('Rendered')} opened_callback={() => console.log('Challenge opened')} closed_callback={() => console.log('Challenge closed')} error_callback={() => console.log('Error occurred')} reset_callback={() => console.log('Widget reset')} expired_callback={() => console.log('Token expired')} chlexpired_callback={() => console.log('Challenge expired')} url_failed_callback={(info) => console.log('URL failed:', info.url)} script_loading_failed_callback={(info) => console.log('All URLs failed:', info.urls)} /> ``` -------------------------------- ### Minimal ArcaptchaWidget Configuration Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md This is the most basic configuration, requiring only the site-key. All other settings will use their default values. ```javascript import { ArcaptchaWidget } from 'arcaptcha-react'; ``` -------------------------------- ### ArcaptchaWidget with Custom Script URL Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Replace the default Arcaptcha API script URL and disable fallback URLs by specifying a custom CDN URL. This is useful for custom CDN setups or testing. ```javascript ``` -------------------------------- ### Basic Visible Widget with Callback Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/api-reference/ArcaptchaWidget.md Integrate a visible ArcaptchaWidget into a form and handle successful verification using a callback function. Ensure to replace 'YOUR_SITE_KEY' with your actual site key. ```javascript import React, { Component, createRef } from 'react'; import { ArcaptchaWidget } from 'arcaptcha-react'; class MyForm extends Component { constructor(props) { super(props); this.arcaptchaRef = createRef(); } handleCaptchaSuccess = (token) => { console.log('User verified. Token:', token); // Send token to your backend for server-side verification }; handleSubmit = (e) => { e.preventDefault(); // Submit form with token }; render() { return (
); } } export default MyForm; ``` -------------------------------- ### execute() Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/api-reference/ArcaptchaWidget.md Programmatically trigger the CAPTCHA challenge. This method returns a promise that resolves with the verification token and site key, or rejects if the widget is not initialized or the challenge fails. It's useful for triggering challenges in invisible mode or forcing a new challenge in visible mode. ```APIDOC ## execute() ### Description Programmatically trigger the CAPTCHA challenge. Returns a promise that resolves with the verification token and site key, or rejects if the widget is not initialized or the challenge fails. Can be used in invisible mode to trigger the challenge without user interaction, or in visible mode to force a new challenge. ### Method `execute(): Promise` ### Parameters None ### Return Type `Promise` ### Return Object Shape ```json { "arcaptcha_token": "string", // The verification token "site_key": "string" // Your site key (echoed back) } ``` ### Throws/Rejects Rejects if the widget is not initialized or the challenge fails. ### Example ```javascript import React, { useRef } from 'react'; import { ArcaptchaWidget } from 'arcaptcha-react'; function MyComponent() { const arcaptchaRef = useRef(null); const handleSubmit = async (e) => { e.preventDefault(); try { const response = await arcaptchaRef.current.execute(); console.log('Token:', response.arcaptcha_token); // Send token to your backend for verification } catch (error) { console.error('CAPTCHA failed:', error); } }; return (
); } ``` ``` -------------------------------- ### Key Methods (via ref) Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/INDEX.md These methods can be accessed using a ref attached to the ArcaptchaWidget component, allowing programmatic control over the captcha. ```APIDOC ## Key Methods (via ref) These methods are accessible via a ref attached to the `ArcaptchaWidget` component. ### `execute()` **Description:** Triggers the captcha verification process, especially useful in invisible mode. **Returns:** A Promise that resolves with an object containing `arcaptcha_token` and `site_key` upon successful verification. **Usage Example (Invisible Mode):** ```javascript const arcaptchaRef = useRef(null); // ... later in your code ... async function verifyCaptcha() { try { const response = await arcaptchaRef.current.execute(); console.log('Captcha Token:', response.arcaptcha_token); } catch (error) { console.error('Captcha execution failed:', error); } } ``` ### `resetCaptcha()` **Description:** Resets the captcha to its initial state, clearing any previous verification status. **Usage Example:** ```javascript arcapchaRef.current.resetCaptcha(); ``` ### `close()` **Description:** Closes the captcha challenge modal if it is currently open. **Usage Example:** ```javascript arcapchaRef.current.close(); ``` ``` -------------------------------- ### Invisible ArcaptchaWidget Mode with Promise Execution Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Configure the widget to run in invisible mode and trigger verification later using a promise-based approach with a ref. ```javascript const arcaptchaRef = useRef(null); // Later, trigger verification: const response = await arcaptchaRef.current.execute(); ``` -------------------------------- ### ARCaptcha Widget Configuration with Callbacks Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Configure ARCaptcha widgets with site key and various callbacks for error handling, token expiration, and script loading failures. Use these callbacks to inform users about verification status. ```javascript { // Handle verification errors showUserNotification('Verification failed. Please try again.'); }} expired_callback={() => { // Handle token expiration showUserNotification('Verification expired. Please complete again.'); }} script_loading_failed_callback={() => { // Handle complete script loading failure showUserNotification( 'Unable to load security verification. ' ); }} /> ``` -------------------------------- ### Basic Visible Arcaptcha Widget Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/INDEX.md Use this snippet to render a basic visible Arcaptcha widget. Ensure you replace 'YOUR_SITE_KEY' with your actual site key. The `callback` prop is used to handle successful verification by logging the received token. ```javascript console.log('Token:', token)} /> ``` -------------------------------- ### Execute Invisible Arcaptcha with Promise Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/INDEX.md This snippet demonstrates how to execute an invisible Arcaptcha verification using a ref. It utilizes an `async/await` pattern to handle the promise returned by the `execute()` method, logging the `arcaptcha_token` upon successful verification. ```javascript const response = await arcaptchaRef.current.execute(); console.log(response.arcaptcha_token); ``` -------------------------------- ### ArcaptchaWidget API Reference Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/SUMMARY.txt Documentation for the ArcaptchaWidget component, including its props and ref handle methods. ```APIDOC ## ArcaptchaWidget Component ### Description The main export for the ARCAPTCHA React integration. This component provides the interface for users to interact with the CAPTCHA functionality. ### Props #### Required - **site-key** (string) - Required - Your unique ARCAPTCHA site key. #### Appearance - **theme** (string) - Optional - Sets the visual theme of the widget (e.g., 'light', 'dark'). - **lang** (string) - Optional - Specifies the language for the CAPTCHA challenge. - **color** (string) - Optional - Customizes the widget's color scheme. #### Behavior - **invisible** (boolean) - Optional - If true, the widget operates in invisible mode, triggering challenges programmatically. - **domain** (string) - Optional - The domain where the widget is being used, for security purposes. - **api_url** (string) - Optional - Custom URL for the ARCAPTCHA API endpoint. - **timeout** (number) - Optional - Timeout duration for API requests. #### Callbacks - **onSuccess** (function) - Callback function executed upon successful CAPTCHA verification. - **onError** (function) - Callback function executed when an error occurs. - **onClose** (function) - Callback function executed when the challenge modal is closed. - (11 different event callbacks documented in total) #### Error Handling Callbacks - **url_failed_callback** (function) - Callback for when the ARCAPTCHA script fails to load. - **script_loading_failed_callback** (function) - Callback for when the ARCAPTCHA script fails to load. ### Ref Handle Methods #### `execute()` - **Description**: Triggers the CAPTCHA challenge programmatically. Useful for invisible mode. - **Usage**: Call this method via the widget's ref. #### `resetCaptcha()` - **Description**: Resets the widget's state, allowing for a new challenge. - **Usage**: Call this method via the widget's ref. #### `close()` - **Description**: Closes the challenge modal if it is currently open. - **Usage**: Call this method via the widget's ref. ### Usage Examples - Basic visible CAPTCHA with callback - Invisible mode with promise-based execute() - With URL failure monitoring - With all callbacks configured - TypeScript examples ``` -------------------------------- ### ArcaptchaWidget with Language and Theme Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Configure the widget to be localized to English and use a dark theme. ```javascript ``` -------------------------------- ### Invisible Mode with Promise Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/api-reference/ArcaptchaWidget.md Implement an invisible ArcaptchaWidget that executes on form submission and returns a promise with the verification token. This is useful for forms where a visible widget is not desired. Replace 'YOUR_SITE_KEY' with your actual site key. ```javascript import React, { useRef } from 'react'; import { ArcaptchaWidget } from 'arcaptcha-react'; export default function InvisibleForm() { const arcaptchaRef = useRef(null); const handleFormSubmit = async (e) => { e.preventDefault(); try { const { arcaptcha_token, site_key } = await arcaptchaRef.current.execute(); console.log('Verification successful'); console.log('Token:', arcaptcha_token); console.log('Site Key:', site_key); // Send token to backend const response = await fetch('/api/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: arcaptcha_token }) }); if (response.ok) { alert('Form submitted successfully!'); } } catch (error) { console.error('CAPTCHA verification failed:', error); arcaptchaRef.current.resetCaptcha(); } }; return (
); } ``` -------------------------------- ### Basic Arcaptcha Widget Usage Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/README.md Integrate the Arcaptcha widget with a site key and callback function. The theme and language are optional props. ```javascript import React from "react"; import { ArcaptchaWidget } from "arcaptcha-react"; class YOUR_COMPONENT_NAME extends Component { constructor() { super(); this.ArRef = React.createRef(); } getToken = (token) => { //do something with your token. }; render() { return (
); } } ``` -------------------------------- ### ScriptLoadingFailedInfo Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Information object passed to the script_loading_failed_callback. ```APIDOC ## ScriptLoadingFailedInfo (script_loading_failed_callback parameter) ### Description Details provided when the Arcaptcha script fails to load. ### Fields - **urls**: string[] - An array of URLs that were attempted to load. - **error**: string - The error message associated with the script loading failure. ``` -------------------------------- ### Global Script Loading Coordination Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/README.md Shows how the ArCaptcha component uses a global promise to ensure the Arcaptcha script is loaded only once across multiple instances. ```javascript window.arcaptchaWidgetLoading = Promise.resolve() // Set after successful load ``` -------------------------------- ### Programmatically Trigger CAPTCHA Challenge Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/api-reference/ArcaptchaWidget.md Use the execute() method to programmatically trigger the CAPTCHA challenge. This is useful in invisible mode to initiate the challenge without user interaction or in visible mode to force a new challenge. It returns a promise that resolves with the verification token. ```javascript import React, { useRef } from 'react'; import { ArcaptchaWidget } from 'arcaptcha-react'; function MyComponent() { const arcaptchaRef = useRef(null); const handleSubmit = async (e) => { e.preventDefault(); try { const response = await arcaptchaRef.current.execute(); console.log('Token:', response.arcaptcha_token); // Send token to your backend for verification } catch (error) { console.error('CAPTCHA failed:', error); } }; return (
); } ``` -------------------------------- ### Theme Values Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Literal type values for the theme prop. ```APIDOC ## Theme Values ```typescript type Theme = 'light' | 'dark' ``` Default: `'light'` Determines the visual appearance of the widget. Light theme suitable for light backgrounds; dark theme suitable for dark backgrounds. ``` -------------------------------- ### Theme Literal Type Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Defines the possible values for the widget's theme. Use 'light' for light backgrounds and 'dark' for dark backgrounds. ```typescript type Theme = 'light' | 'dark' ``` -------------------------------- ### Basic Arcaptcha Widget Usage Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/README.md Integrate the ArcaptchaWidget component for visible CAPTCHA verification. Requires a site key and a callback function to handle the verification token. ```javascript import { ArcaptchaWidget } from 'arcaptcha-react'; function MyForm() { const handleToken = (token) => { console.log('Verified with token:', token); }; return ( ); } ``` -------------------------------- ### ArcaptchaWidgetHandle Interface Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/SUMMARY.txt Defines the methods available on the ArcaptchaWidget component's ref handle. ```APIDOC ## ArcaptchaWidgetHandle Interface ### Description This interface defines the methods that can be accessed through the ref of an ArcaptchaWidget component. ### Methods - **execute()**: Triggers the CAPTCHA challenge. - **resetCaptcha()**: Resets the widget's state. - **close()**: Closes the challenge modal. ``` -------------------------------- ### Invisible Arcaptcha with Promise Execution and Reset Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/README.md Illustrates using an invisible Arcaptcha widget with promise-based execution and reset methods in a functional component. Handles success and error scenarios for CAPTCHA execution. ```typescript import React, { useRef } from 'react'; import { ArcaptchaWidget, ArcaptchaWidgetHandle } from 'arcaptcha-react'; const ArcaptchaReact: React.FC = () => { const arcaptchaRef = useRef(null); const execute = async () => { console.log('Execute button clicked'); try { const token= await arcaptchaRef.current?.execute(); console.log('Arcaptcha_token:', token?.arcaptcha_token); console.log('Site_key:', token?.site_key); } catch (err) { console.error('Error executing captcha:', err); } }; const reset = () => { console.log('Reset button clicked'); arcaptchaRef.current?.resetCaptcha(); }; return (
); }; export default ArcaptchaReact; ``` -------------------------------- ### ArcaptchaWidget with Extended Timeout Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Configure a longer timeout (20 seconds) for each fallback URL, which can be beneficial for users with poor network connectivity. ```javascript ``` -------------------------------- ### Import All Arcaptcha React JS Types Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Import all available types and the ArcaptchaWidget component from the main package entry point. This is useful when you need access to multiple types and the widget itself. ```typescript import { ArcaptchaWidget, ArcaptchaWidgetProps, ArcaptchaWidgetHandle, ArcaptchaExecuteResponse, UrlFailureInfo, ScriptLoadingFailedInfo } from 'arcaptcha-react' ``` -------------------------------- ### UrlFailureInfo Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Information object passed to the url_failed_callback. ```APIDOC ## UrlFailureInfo (url_failed_callback parameter) ### Description Details provided when a URL fails to load during widget operation. ### Fields - **url**: string - The URL that failed to load. - **error**: string - The error message associated with the failure. - **attemptNumber**: number - The current attempt number. - **totalAttempts**: number - The total number of attempts made. - **isLastAttempt**: boolean - Indicates if this was the last attempt. ``` -------------------------------- ### Monitoring Arcaptcha URL Failures Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Configure callbacks to monitor individual URL failures and complete script loading failures. Provides detailed information about failed attempts and allows for user-friendly error handling. ```javascript { console.warn( `CAPTCHA URL failed: ${info.url} ` + `(Attempt ${info.attemptNumber} of ${info.totalAttempts})` ); if (info.isLastAttempt) { // Show user-friendly error after all URLs fail showUserNotification('Unable to load security verification'); } }} script_loading_failed_callback={(info) => { console.error('CAPTCHA script loading completely failed'); console.error('Attempted URLs:', info.urls); }} /> ``` -------------------------------- ### ArcaptchaExecuteResponse Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Represents the response object returned when the `execute()` method of ArcaptchaWidgetHandle completes successfully, containing the verification token and site key. ```APIDOC ## ArcaptchaExecuteResponse ### Description Response object returned when `execute()` method completes successfully. ### Fields - **arcaptcha_token** (`string`) - The verification token from Arcaptcha. Send this to your backend for verification. - **site_key** (`string`) - Your site key, echoed back in the response for confirmation. ### Example Usage ```typescript try { const response = await arcaptchaRef.current?.execute(); const token = response.arcaptcha_token; const siteKey = response.site_key; // Send token to backend for verification await backend.verifyToken(token); } catch (error) { console.error('Verification failed:', error); } ``` ``` -------------------------------- ### ArcaptchaWidgetHandle Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Provides an interface for programmatic control of the Arcaptcha widget, allowing users to trigger challenges, reset the widget, and optionally close the challenge modal. ```APIDOC ## ArcaptchaWidgetHandle ### Description Ref handle interface for programmatic control of the widget. ### Methods - **execute**: `() => Promise` - Triggers the CAPTCHA challenge programmatically. Returns a promise resolving with the verification response. - **resetCaptcha**: `() => void` - Resets the widget to initial state, clearing any token. - **close**: `() => void` - Closes the challenge modal if open. Optional. ### Example Usage ```typescript const arcaptchaRef = useRef(null); // Trigger challenge const response = await arcaptchaRef.current?.execute(); console.log(response.arcaptcha_token); // Reset widget arcaptchaRef.current?.resetCaptcha(); // Close modal arcaptchaRef.current?.close(); ``` ``` -------------------------------- ### Import ArcaptchaWidget Component Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/README.md Import the ArcaptchaWidget component from the 'arcaptcha-react' library. This is the primary way to use the widget in your React application. ```typescript import { ArcaptchaWidget } from 'arcaptcha-react' ``` -------------------------------- ### Error Handling Types Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/SUMMARY.txt Details on error types, conditions, and recovery strategies. ```APIDOC ## Error Handling ### Description This section covers all error types and conditions encountered with the ARCAPTCHA widget, along with recommended recovery strategies and best practices. ### Error Types and Conditions - Script loading errors (with fallback strategy) - Verification errors - Token and challenge expiration - Widget blocking scenarios ### Callbacks - **onError** (function): General error callback. - **url_failed_callback** (function): Specific callback for script URL load failures. - **script_loading_failed_callback** (function): Specific callback for script loading failures. ### Recovery Strategies - Implement fallback mechanisms for script loading. - Provide user feedback on verification or token expiration errors. - Guide users through re-challenge or reset procedures. ### Best Practices - Comprehensive error logging. - User-friendly error messages. - Graceful degradation when errors occur. ``` -------------------------------- ### Arcaptcha Widget with URL Failure Monitoring Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/README.md Configure Arcaptcha widget with custom timeout and callbacks for URL loading failures and script loading failures. Useful for debugging and handling network issues. ```javascript import React from "react"; import { ArcaptchaWidget } from "arcaptcha-react"; class YOUR_COMPONENT_NAME extends Component { constructor() { super(); this.ArRef = React.createRef(); } getToken = (token) => { //do something with your token. }; handleUrlFailure = (info) => { console.log(`URL failed: ${info.url}`); console.log(`Error: ${info.error}`); console.log(`Attempt ${info.attemptNumber} of ${info.totalAttempts}`); if (info.isLastAttempt) { console.log("All URLs failed to load"); } }; handleScriptLoadingFailed = (info) => { console.log("All fallback URLs failed"); console.log(`Last error: ${info.error}`); console.log(`Tried URLs: ${info.urls.join(", ")}`); }; render() { return (
); } } ``` -------------------------------- ### Invisible Arcaptcha Widget with Promise Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/README.md Utilize the invisible Arcaptcha widget with promise-based execution for handling the captcha token asynchronously. Includes methods to execute and reset. ```javascript import React from "react"; import { ArcaptchaWidget } from "arcaptcha-react"; class ArcaptchaReact extends React.Component { constructor() { super(); this.ArRef = React.createRef(); } execute = () => { this.ArRef.current.execute().then((token) => { console.log(token); }); }; reset = () => { this.ArRef.current.resetCaptcha(); }; render() { return (
); } } export default ArcaptchaReact; ``` -------------------------------- ### Content Security Policy Configuration Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Adjust your application's Content Security Policy (CSP) to allow Arcaptcha script sources. This is necessary if your CSP restricts external script loading. ```http script-src 'unsafe-inline' https://widget.arcaptcha.ir https://widget.arcaptcha.net https://widget.arcaptcha.co; ``` -------------------------------- ### Size Values (Deprecated) Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Literal type values for the size prop, now deprecated in favor of the invisible prop. ```APIDOC ## Size Values ```typescript type Size = 'normal' | 'invisible' ``` Controls widget visibility. Typically use the `invisible` boolean prop instead of this deprecated field. ``` -------------------------------- ### Language Values Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Literal type values for the lang prop. ```APIDOC ## Language Values ```typescript type Language = 'en' | 'fa' ``` Default: `'fa'` (Persian) Localizes the widget UI and challenge interface: - `'en'`: English - `'fa'`: Persian (Farsi) ``` -------------------------------- ### Peer Dependencies Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/README.md Specifies the peer dependency on React for the Arcaptcha component. ```json { "react": ">=16.8.0" } ``` -------------------------------- ### Arcaptcha Widget Error Handling Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/INDEX.md Implement robust error handling for Arcaptcha widgets using the `script_loading_failed_callback` and `error_callback` props. The former logs detailed information about failed script URLs, while the latter is invoked upon general verification failures. ```javascript { console.error('All URLs failed:', info.urls); }} error_callback={() => console.error('Verification failed')} /> ``` -------------------------------- ### ArcaptchaWidgetHandle Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Reference handle for the Arcaptcha React component, providing methods to control the widget. ```APIDOC ## ArcaptchaWidgetHandle (ref handle) ### Description Methods available through the ref handle of the Arcaptcha widget. ### Methods - **execute()**: Promise - Executes the Arcaptcha challenge and returns a promise that resolves with the response. - **resetCaptcha()**: void - Resets the Arcaptcha widget. - **close()**: void - Closes the Arcaptcha challenge interface. ``` -------------------------------- ### close() Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/api-reference/ArcaptchaWidget.md Programmatically closes the CAPTCHA challenge modal. This method is only effective in visible mode when a challenge is actively displayed and has no effect if the challenge is not open. ```APIDOC ## close() ### Description Programmatically closes the CAPTCHA challenge modal if it is currently open. Only has an effect in visible mode when a challenge is actively displayed. Does nothing if the challenge is not open. ### Method `close(): void` ### Parameters None ### Return Type `void` ### Example ```javascript import React, { useRef } from 'react'; import { ArcaptchaWidget } from 'arcaptcha-react'; function MyComponent() { const arcaptchaRef = useRef(null); const handleClose = () => { arcaptchaRef.current.close(); }; return (
); } ``` ``` -------------------------------- ### ArcaptchaWidgetProps Interface Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/SUMMARY.txt Defines the properties (props) that can be passed to the ArcaptchaWidget component. ```APIDOC ## ArcaptchaWidgetProps Interface ### Description This interface outlines all the configurable properties for the ArcaptchaWidget component. ### Props #### Required - **site-key** (string) - Your unique ARCAPTCHA site key. #### Optional - **theme** (string) - Widget visual theme (e.g., 'light', 'dark'). - **lang** (string) - Language for the CAPTCHA challenge. - **color** (string) - Customizes the widget's color scheme. - **invisible** (boolean) - Enables invisible mode. - **domain** (string) - Domain for security validation. - **api_url** (string) - Custom ARCAPTCHA API endpoint URL. - **timeout** (number) - Timeout duration for API requests. - **onSuccess** (function) - Callback on successful verification. - **onError** (function) - Callback on error. - **onClose** (function) - Callback when the modal is closed. - **url_failed_callback** (function) - Callback for script URL load failures. - **script_loading_failed_callback** (function) - Callback for script loading failures. ``` -------------------------------- ### resetCaptcha() Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/api-reference/ArcaptchaWidget.md Resets the CAPTCHA widget to its initial state, clearing the current CAPTCHA state and token. This ensures the user must complete the challenge again and triggers the `reset_callback` if provided. It functions in both visible and invisible modes. ```APIDOC ## resetCaptcha() ### Description Resets the CAPTCHA widget to its initial state, clearing the current CAPTCHA state and token. The user will need to complete the CAPTCHA challenge again. Triggers the `reset_callback` if provided. Works in both visible and invisible modes. ### Method `resetCaptcha(): void` ### Parameters None ### Return Type `void` ### Example ```javascript import React, { useRef } from 'react'; import { ArcaptchaWidget } from 'arcaptcha-react'; function MyComponent() { const arcaptchaRef = useRef(null); const handleReset = () => { arcaptchaRef.current.resetCaptcha(); }; return (
); } ``` ``` -------------------------------- ### Dynamic Import for SSR with Next.js Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/configuration.md Use dynamic import to prevent Arcaptcha component rendering on the server. This ensures the component only loads on the client side. ```javascript import dynamic from 'next/dynamic'; const ArcaptchaWidget = dynamic( () => import('arcaptcha-react').then(mod => mod.ArcaptchaWidget), { ssr: false } ); ``` -------------------------------- ### ArcaptchaExecuteResponse Interface Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Defines the structure of the response object returned upon successful execution of the CAPTCHA challenge. Contains the verification token and site key. ```typescript interface ArcaptchaExecuteResponse { arcaptcha_token: string site_key: string } ``` -------------------------------- ### Size Literal Type Source: https://github.com/arcaptcha/arcaptcha-react-js/blob/main/_autodocs/types.md Defines the possible values for widget size. This field is deprecated; use the 'invisible' boolean prop instead. ```typescript type Size = 'normal' | 'invisible' ```