### Example Server Plan Response Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md Provides an example of a Server Plan object, detailing plan name, available credits, quota, and timing information for the current period. ```javascript { plan: "Starter", credit: 500, quota: 1000, duration: 2592000, // 30 days lastreset: 1234567890, current_period_start: 1234567890, current_period_end: 1237159890 } ``` -------------------------------- ### Example URL for Settings Import Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md This URL demonstrates how to encode API key and settings like boolean values, integer delays, and JSON-encoded arrays for disabled hosts. ```url https://nopecha.com/setup#my-api-key-123|enabled=true|hcaptcha_solve_delay_time=5000|disabled_hosts=%5B%22example.com%22%5D ``` -------------------------------- ### RunningAs Enum Usage Example Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md Example of how to import and use the RunningAs enum to conditionally execute code based on the script's context. ```javascript import {runningAt, RunningAs} from './utils.mjs'; if (runningAt === RunningAs.BACKGROUND) { // Initialize background-only features } ``` -------------------------------- ### Get Current Settings Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/configuration.md Retrieve the current extension settings from persistent storage. This is the first step before modifying any settings. ```javascript // Get current settings const settings = await BG.exec('Settings.get'); ``` -------------------------------- ### Start Extension in Automation with Puppeteer Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/00-START-HERE.md Launch Puppeteer with the extension loaded. The extension will automatically solve CAPTCHAs on the page. ```javascript // Puppeteer example const browser = await puppeteer.launch({ args: ['--disable-extensions-except=/path/to/extension', '--load-extension=/path/to/extension'] }); // The extension automatically solves CAPTCHAs on the page ``` -------------------------------- ### Reset Settings to Defaults Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/configuration.md Revert all extension settings back to their default values. This is useful for troubleshooting or starting fresh. ```javascript // Reset to defaults await BG.exec('Settings.reset'); ``` -------------------------------- ### Submit Job with NopeCHA.post() Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md Example of how to submit a job using NopeCHA.post() and check if a job_id was successfully returned. ```javascript const result = await NopeCHA.post({...}); if (result.job_id) { console.log('Job submitted:', result.job_id); } ``` -------------------------------- ### Get Extension Settings Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Retrieves the current extension settings. Use this to access configuration values like API keys or enabled features. ```javascript const settings = await BG.exec('Settings.get'); console.log(settings.enabled); // boolean console.log(settings.key); // string (API key) ``` -------------------------------- ### Example CAPTCHA Handler Skeleton Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/captcha-handlers.md This skeleton demonstrates the common lifecycle of a CAPTCHA handler, including detection, task extraction, API submission, and solution entry. It is designed to be injected into CAPTCHA provider frames. ```javascript (async () => { // 1. Detection functions function is_widget_frame() { return document.querySelector('.captcha-widget') !== null; } function is_image_frame() { return document.querySelector('.captcha-challenge') !== null; } function is_solved() { return document.querySelector('.captcha-success') !== null; } // 2. Task extraction async function get_task() { const taskEl = document.querySelector('.challenge-text'); return taskEl?.innerText?.trim() || null; } async function get_image_urls() { const $images = document.querySelectorAll('.challenge-cell img'); return Array.from($images).map(img => img.src).filter(src => src); } // 3. Solution submission async function submit_solution(indices) { const $cells = document.querySelectorAll('.challenge-cell'); for (const idx of indices) { $cells[idx]?.click(); } document.querySelector('.submit-button')?.click(); } // 4. Main loop async function solve() { // Check if already solved if (is_solved()) return; // Wait for challenge to load const challenge = await on_task_ready(); if (!challenge) return; // Submit to NopeCHA const settings = await BG.exec('Settings.get'); const result = await NopeCHA.post({ captcha_type: 'my_captcha_image', task: challenge.task, image_urls: challenge.urls, key: settings.key }); // Enter solution if (result.data) { await submit_solution(result.data); } } // 5. Start solving await solve(); })(); ``` -------------------------------- ### Replace All Settings Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/configuration.md Completely replace all current settings with a new set of settings. Ensure the new settings object is a deep copy, for example, using structuredClone. ```javascript // Replace all settings const newSettings = structuredClone(SettingsManager.DEFAULT); newSettings.key = 'new-key'; await BG.exec('Settings.replace', {settings: newSettings}); ``` -------------------------------- ### Get Browser Version Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Returns the browser platform identifier, either 'chrome' or 'firefox'. Useful for browser-specific logic. ```javascript static async version() -> string ``` ```javascript const version = await BG.exec('Browser.version'); if (version === 'chrome') { // Chrome-specific code } ``` -------------------------------- ### Example hCaptcha Response for NopeCHA.get() Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md Illustrates a typical response structure for a hCaptcha solution retrieved via NopeCHA.get(), showing job ID, cell indices, and confidence metadata. ```javascript { job_id: "8f4e5d2c", data: [0, 2, 5], // Indices of selected cells metadata: {confidence: 0.92} } ``` -------------------------------- ### Get Current Page Hostname Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/content-script-api.md Retrieves the hostname of the currently active webpage. Provides the domain of the page the content script is running on. ```javascript static async hostname() -> string ``` ```javascript const currentHost = await Location.hostname(); console.log(currentHost); // "example.com" ``` -------------------------------- ### Time Utilities Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/content-script-api.md Provides static methods for handling time-related operations such as getting the current timestamp, sleeping for a duration, and formatting time values. ```APIDOC ## Time Utilities ### Description Provides static methods for handling time-related operations such as getting the current timestamp, sleeping for a duration, and formatting time values. ### Methods - `static time() -> number` - Description: Get the current timestamp. - `static date() -> Date` - Description: Get the current Date object. - `static sleep(ms=1000) -> Promise` - Description: Sleep for a specified number of milliseconds. - `static async random_sleep(min, max) -> Promise` - Description: Sleep for a random duration between min and max milliseconds. - `static seconds_as_hms(seconds) -> string` - Description: Format a given number of seconds into HH:MM:SS format. - `static string(date=null) -> string` - Description: Format a date object into MM/DD/YYYY HH:MM:SS AM/PM format. Defaults to the current date if null. ### Example ```javascript await Time.sleep(2000); // Wait 2 seconds const formatted = Time.seconds_as_hms(3661); // "01:01:01" ``` ``` -------------------------------- ### Data Flow from Webpage to NopeCHA API Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/OVERVIEW.md Illustrates the data flow starting from a content script on a webpage, communicating with the background worker, which then interacts with various API classes before sending requests to the NopeCHA API. ```mermaid graph TD Webpage (Content Script) [message via chrome.runtime.sendMessage] Background Worker (BG class) [API lookup and execution] API Class Methods (Settings, Cache, Net, Tab, Icon, etc.) [results via callback] Content Script [page interaction] NopeCHA API (HTTPS) ``` -------------------------------- ### Base Content Script Configuration (All URLs) Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/manifest-reference.md Configures content scripts to run on all URLs at document_start, loading utility and content scripts for message handling and background communication. ```json { "matches": [""], "js": ["utils.js", "content.js"], "run_at": "document_start", "all_frames": true, "match_about_blank": true } ``` -------------------------------- ### Server.get_plan Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Fetches the API plan and credit information from the NopeCHA server. ```APIDOC ## Server.get_plan ### Description Fetches the API plan and credit information from the NopeCHA server. ### Method `BG.exec('Server.get_plan', {key})` ### Parameters #### Path Parameters - **key** (string) - Required - API key (empty string for free tier) ### Returns Plan object with keys: - `plan` (string): Plan name (e.g., "Starter", "Basic", "Unknown") - `credit` (number): Available credits - `quota` (number): API request quota - `duration` (number): Plan duration in seconds - `lastreset` (number): Last reset timestamp - `current_period_start` (number): Period start timestamp - `current_period_end` (number): Period end timestamp - `error` (string, optional): Error message if request failed ### Request Example ```javascript const plan = await BG.exec('Server.get_plan', {key: 'my-api-key'}); console.log(plan.plan); // "Basic Plan" console.log(plan.credit); // 500 ``` ``` -------------------------------- ### NopeCHA API Timeouts Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/content-script-api.md Constants defining the maximum wait times in seconds for POST and GET requests. ```javascript static MAX_WAIT_POST = 60 // POST request timeout ``` ```javascript static MAX_WAIT_GET = 60 // GET polling timeout ``` -------------------------------- ### SettingsManager.import Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/utilities.md Parses a URL-encoded settings hash string and reconstructs the settings object. Missing fields are populated with default values. ```APIDOC ## SettingsManager.import(encoded_hash) ### Description Parses URL-encoded settings hash and returns settings object. ### Method `static import(encoded_hash) -> object` ### Parameters #### Path Parameters - **encoded_hash** (string) - Required - Hash string (with or without leading `#`) ### Request Example ```javascript const hash = 'my-key|enabled=true|hcaptcha_solve_delay_time=5000'; const settings = SettingsManager.import(hash); // {key: 'my-key', enabled: true, hcaptcha_solve_delay_time: 5000, ...defaults...} ``` ### Response #### Success Response (object) Parsed settings object (missing fields filled from defaults). ``` -------------------------------- ### Get Current Timestamp Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/utilities.md Returns the current timestamp in milliseconds since the epoch. Useful for measuring elapsed time. ```javascript static time() -> number ``` ```javascript const start = Time.time(); // ... do something ... const elapsed = Time.time() - start; ``` -------------------------------- ### FunCAPTCHA Fast Initialization Script Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/manifest-reference.md Injects early hooks for FunCAPTCHA initialization at document_start on specified Arkoselabs and Funcaptcha domains. Includes support for about:blank. ```json { "matches": ["*://*.arkoselabs.com/fc/*", "*://*.funcaptcha.com/fc/*"], "js": ["funcaptcha_fast.js"], "run_at": "document_start", "all_frames": true, "match_about_blank": true } ``` -------------------------------- ### Server Plan Object Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md This object details the current server plan information, including plan name, available credits, quota, and relevant timestamps for the billing period. ```APIDOC ## Server Plan Object ### Description This object details the current server plan information, including plan name, available credits, quota, and relevant timestamps for the billing period. ### Response #### Success Response - **plan** (string) - Plan name (e.g., "Starter", "Unknown"). - **credit** (number) - Available credits. - **quota** (number) - Current period quota. - **duration** (number) - Plan duration in seconds. - **lastreset** (number) - Last reset timestamp (seconds). - **current_period_start** (number) - Period start timestamp. - **current_period_end** (number) - Period end timestamp. - **error** (string) - Error message if request failed (optional). ### Example ```javascript { "plan": "Starter", "credit": 500, "quota": 1000, "duration": 2592000, // 30 days "lastreset": 1234567890, "current_period_start": 1234567890, "current_period_end": 1237159890 } ``` ``` -------------------------------- ### Build Manifest Script Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/manifest-reference.md Executes the Python script to generate platform-specific manifest files from a base manifest. ```bash python build.py ``` -------------------------------- ### reCAPTCHA Fast Initialization Script Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/manifest-reference.md Injects early hooks for reCAPTCHA initialization at document_start on specified Google and recaptcha.net domains. ```json { "matches": ["*://*.google.com/recaptcha/*", "*://*.recaptcha.net/recaptcha/*", "*://recaptcha.net/recaptcha/*"], "js": ["recaptcha_fast.js"], "run_at": "document_start", "all_frames": true } ``` -------------------------------- ### Get Active Tab Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Retrieves the currently active tab in the browser. Returns a promise that resolves with the active tab object. ```javascript static active() -> Promise ``` ```javascript const activeTab = await BG.exec('Tab.active'); console.log(activeTab.id); ``` -------------------------------- ### Settings.get() Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Retrieves the current extension settings. This method returns an object containing various configuration options. ```APIDOC ## Settings.get() ### Description Returns the current settings object. ### Method `BG.exec('Settings.get')` ### Parameters None ### Returns Object with keys: `version`, `key`, `enabled`, `disabled_hosts`, and per-CAPTCHA settings (e.g., `hcaptcha_auto_open`, `recaptcha_solve_delay_time`). ### Example ```javascript const settings = await BG.exec('Settings.get'); console.log(settings.enabled); // boolean console.log(settings.key); // string (API key) ``` ``` -------------------------------- ### Get Tab Information Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Retrieves information about a specific tab using its ID. Returns a tab object or false if the tab is not found. ```javascript static info({tab_id}) -> Promise ``` ```javascript const tabInfo = await BG.exec('Tab.info', {tab_id: 42}); console.log(tabInfo.url); // "https://example.com/page" console.log(tabInfo.title); // Page title ``` -------------------------------- ### Configure Extension Settings Programmatically Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/00-START-HERE.md Access and modify extension settings from a content script. Use BG.exec to interact with background functionalities. ```javascript // From content script const settings = await BG.exec('Settings.get'); await BG.exec('Settings.set', { id: 'enabled', value: false }); ``` -------------------------------- ### Background API - Settings Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/INDEX.md Methods for managing extension settings. ```APIDOC ## Settings.get() ### Description Retrieve all current settings. ### Method `Settings.get()` ### Parameters None ### Response - **settings** (object) - An object containing all current settings. ``` ```APIDOC ## Settings.set({id, value}) ### Description Set a single configuration setting. ### Method `Settings.set({id, value})` ### Parameters - **id** (string) - The ID of the setting to change. - **value** (any) - The new value for the setting. ``` ```APIDOC ## Settings.update({settings}) ### Description Update multiple configuration settings. ### Method `Settings.update({settings})` ### Parameters - **settings** (object) - An object where keys are setting IDs and values are their new values. ``` ```APIDOC ## Settings.replace({settings}) ### Description Replace all configuration settings with a new set. ### Method `Settings.replace({settings})` ### Parameters - **settings** (object) - An object containing the new set of all settings. ``` ```APIDOC ## Settings.reset() ### Description Reset all settings to their default values. ### Method `Settings.reset()` ### Parameters None ``` -------------------------------- ### Fetch URL with Options Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Fetches a URL using provided options and returns the response text. Returns `null` if the fetch fails. Handles various HTTP methods and request bodies. ```javascript const html = await BG.exec('Net.fetch', { url: 'https://example.com/api/data' }); ``` ```javascript const json = await BG.exec('Net.fetch', { url: 'https://api.example.com/submit', options: { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({key: 'value'}) } }); ``` -------------------------------- ### Get Current Date Object Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/utilities.md Returns a new Date object representing the current time. Useful for accessing date and time components. ```javascript static date() -> Date ``` ```javascript const now = Time.date(); console.log(now.getHours()); // Current hour ``` -------------------------------- ### Base Manifest Configuration Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/manifest-reference.md Defines common extension metadata including name, version, description, permissions, icons, and content script rules. ```json { "name": "NopeCHA: CAPTCHA Solver", "version": "0.3.3", "description": "Automatically solve reCAPTCHA, hCaptcha, FunCAPTCHA, AWS WAF, and text CAPTCHA using AI.", "permissions": [ "storage", "scripting", "contextMenus" ], "icons": { "16": "icon/16.png", "32": "icon/32.png", "48": "icon/48.png", "128": "icon/128.png" }, "content_scripts": [...] } ``` -------------------------------- ### Server Plan Object Interface Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md Defines the structure of the Server Plan object returned by Server.get_plan({key}). It includes details about the plan, credits, quota, and duration. ```typescript interface PlanObject { plan: string; // Plan name (e.g., "Starter", "Unknown") credit: number; // Available credits quota: number; // Current period quota duration: number; // Plan duration in seconds lastreset: number; // Last reset timestamp (seconds) current_period_start: number; // Period start timestamp current_period_end: number; // Period end timestamp error?: string; // Error message if request failed } ``` -------------------------------- ### Utility Classes - SettingsManager Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/INDEX.md Utilities for exporting and importing settings. ```APIDOC ## SettingsManager.export(settings) ### Description Export settings into a URL-friendly hash format. ### Method `SettingsManager.export(settings)` ### Parameters - **settings** (object) - The settings object to export. ### Response - **hash** (string) - The exported settings as a hash string. ``` ```APIDOC ## SettingsManager.import(hash) ### Description Import settings from a URL hash string. ### Method `SettingsManager.import(hash)` ### Parameters - **hash** (string) - The hash string containing the settings. ### Response - **settings** (object) - The imported settings object. ``` -------------------------------- ### Get Browser Tab Information Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md Retrieves information about a specific browser tab using its ID. Logs the tab's URL and title to the console. ```javascript const tab = await BG.exec('Tab.info', {tab_id: 42}); console.log(tab.url); // "https://example.com/page" console.log(tab.title); // "Example Page" ``` -------------------------------- ### SettingsManager.DEFAULT Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/utilities.md Provides the default settings object structure. Refer to the Configuration documentation for the full schema. ```javascript static DEFAULT = { version: 15, key: '', enabled: true, disabled_hosts: [], // ... per-CAPTCHA settings } ``` -------------------------------- ### Fetch API Plan and Credits Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Retrieves the user's API plan details, including credits, quota, and duration, from the NopeCHA server. An empty string can be used for the API key to check the free tier. ```javascript static async get_plan({key}) -> Object ``` ```javascript const plan = await BG.exec('Server.get_plan', {key: 'my-api-key'}); console.log(plan.plan); // "Basic Plan" console.log(plan.credit); // 500 ``` -------------------------------- ### Get Cache Value Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Retrieves a cached value. If `tab_specific` is true, the key is prefixed with the tab ID, and `tab_id` must be provided. Returns `undefined` if the value is not found. ```javascript const count = await BG.exec('Cache.get', {name: 'solve_count'}); ``` ```javascript const status = await BG.exec('Cache.get', {tab_id: 42, name: 'status', tab_specific: true}); ``` -------------------------------- ### Settings.update({settings}) Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Updates multiple extension settings simultaneously by merging them with existing values. ```APIDOC ## Settings.update({settings}) ### Description Updates multiple settings at once, merging with existing values. ### Method `BG.exec('Settings.update', {settings})` ### Parameters #### Request Body - **settings** (object) - Required - Object with setting keys and new values ### Returns undefined (void) ### Example ```javascript await BG.exec('Settings.update', { settings: { enabled: true, hcaptcha_solve_delay_time: 4000, recaptcha_auto_solve: false } }); ``` ``` -------------------------------- ### NopeCHA.post() Response Interface Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md Defines the structure of the response object when submitting a job via NopeCHA.post(). The 'job_id' is returned immediately, while 'data' is populated after a successful 'get()' call. ```typescript interface PostResponse { job_id: string | null; // Job identifier, or null on error data: any; // Solution (populated after get() call) } ``` -------------------------------- ### Time Class Utilities Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/captcha-handlers.md Provides utility functions for managing time-related operations, including sleeping for a specified duration, random delays, getting the current timestamp, and formatting seconds into HH:MM:SS. ```javascript Time.sleep(ms) Time.random_sleep(min, max) Time.time() Time.seconds_as_hms(sec) ``` -------------------------------- ### Open a New Tab Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Opens a new browser tab with a specified URL. Returns a promise that resolves when the tab is created. ```javascript static open({url}={url: null}) -> Promise ``` ```javascript const tab = await BG.exec('Tab.open', {url: 'https://example.com'}); ``` -------------------------------- ### Background API - Server Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/INDEX.md Fetch information about the NopeCHA API plan. ```APIDOC ## Server.get_plan({key}) ### Description Fetch the current API plan and remaining credits. ### Method `Server.get_plan({key})` ### Parameters - **key** (string) - Your NopeCHA API key. ### Response - **planInfo** (object) - An object containing plan details and credits. ``` -------------------------------- ### SettingsManager.export(settings) Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/utilities.md Exports a settings object into a URL-encoded hash string. Returns false if the API key is missing. ```javascript static export(settings) -> string | boolean ``` ```javascript const url = SettingsManager.export(settings); // "https://nopecha.com/setup#my-key-123|enabled=true|hcaptcha_solve_delay_time=5000" ``` -------------------------------- ### Settings.set({id, value}) Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Sets a single extension setting. Use this to modify individual configuration options. ```APIDOC ## Settings.set({id, value}) ### Description Sets a single setting value. ### Method `BG.exec('Settings.set', {id, value})` ### Parameters #### Request Body - **id** (string) - Required - Setting key (e.g., `"enabled"`, `"hcaptcha_solve_delay_time"`) - **value** (any) - Required - New value for the setting ### Returns undefined (void) ### Example ```javascript await BG.exec('Settings.set', {id: 'enabled', value: false}); await BG.exec('Settings.set', {id: 'hcaptcha_solve_delay_time', value: 5000}); ``` ``` -------------------------------- ### Import Settings from URL Hash Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/configuration.md This snippet shows the format of a settings hash that can be imported. Field values are URL-encoded for special characters. ```javascript const hash = '#my-api-key|recaptcha_solve_delay_time=5000|hcaptcha_auto_solve=false'; const imported = SettingsManager.import(hash); ``` -------------------------------- ### Icon Management Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Utilities for managing the extension's icon state. ```APIDOC ## Icon.set ### Description Sets the extension icon state (enabled/disabled). ### Method `Icon.set({status})` ### Parameters #### Path Parameters - **status** (string) - Required - `"on"` for enabled icon, `"off"` for disabled (grayscale). ### Returns - `Promise` - Resolves when icon is updated. ### Example ```javascript await BG.exec('Icon.set', {status: 'on'}); await BG.exec('Icon.set', {status: 'off'}); ``` ``` -------------------------------- ### Export Settings to URL Hash Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/configuration.md Use this to generate a URL hash for sharing or backing up current settings. The exported format includes the API key and other settings separated by '|'. ```javascript const SettingsManager = require('utils.mjs').SettingsManager; const url = SettingsManager.export(settings); // Returns: "https://nopecha.com/setup#api-key|key1=val1|key2=val2|..." ``` -------------------------------- ### Background API - Inject Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/INDEX.md Execute code within web pages. ```APIDOC ## Inject.func({tab_id, func, args}) ### Description Execute a JavaScript function within a specific tab. ### Method `Inject.func({tab_id, func, args})` ### Parameters - **tab_id** (number) - The ID of the tab where the function should be executed. - **func** (function) - The function to execute. - **args** (array) - Arguments to pass to the function. ``` ```APIDOC ## Inject.files({tab_id, frame_id, files}) ### Description Inject one or more script files into a specific tab and frame. ### Method `Inject.files({tab_id, frame_id, files})` ### Parameters - **tab_id** (number) - The ID of the tab. - **frame_id** (number) - The ID of the frame within the tab. - **files** (array of strings) - An array of script file paths to inject. ``` -------------------------------- ### Settings.reset() Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Resets all extension settings to their default values. ```APIDOC ## Settings.reset() ### Description Resets all settings to default values (from `SettingsManager.DEFAULT`). ### Method `BG.exec('Settings.reset')` ### Parameters None ### Returns undefined (void) ### Example ```javascript await BG.exec('Settings.reset'); ``` ``` -------------------------------- ### General Utilities Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/content-script-api.md Offers static methods for common utility tasks including string manipulation, parsing, and ID generation. ```APIDOC ## General Utilities ### Description Offers static methods for common utility tasks including string manipulation, parsing, and ID generation. ### Static Properties - `static CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'` - Description: A string containing all uppercase letters, lowercase letters, and digits, used for ID generation. ### Methods - `static pad_left(s, char, n) -> string` - Description: Pad a string `s` on the left with character `char` until it reaches length `n`. - `static capitalize(s) -> string` - Description: Capitalize the first character of a string `s`. - `static parse_int(s, fallback) -> number` - Description: Parse a string `s` into an integer. Returns `fallback` if parsing fails. - `static parse_bool(s, fallback) -> boolean` - Description: Parse a string `s` into a boolean. Returns `fallback` if parsing fails. - `static parse_string(s, fallback) -> string` - Description: Ensure the input `s` is a string. Returns `fallback` if the input cannot be converted to a string. - `static parse_json(s, fallback) -> object` - Description: Parse a string `s` as JSON. Returns `fallback` if JSON parsing fails. - `static generate_id(n) -> string` - Description: Generate a random ID of length `n` using the `CHARS` property. ### Example ```javascript const id = Util.generate_id(8); // "aB3xYzQp" const padded = Util.pad_left(5, '0', 3); // "005" ``` ``` -------------------------------- ### Message Protocol to Background Script Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/captcha-handlers.md Illustrates the message protocol used by handlers to communicate with the background script via BG.exec(). This includes fetching settings, checking if a host is disabled, updating the status badge, encoding images, and logging messages. ```javascript // Get settings const settings = await BG.exec('Settings.get'); // Check if host is disabled const hostname = await Location.hostname(); if (settings.disabled_hosts.includes(hostname)) return; // Update status badge await BG.exec('Icon.set_badge', {tab_id, data: {text: '✓', color: '#4CAF50'}}); // Encode images const base64 = await Image.encode(imageUrl); // Log to background console await BG.exec('Browser.log', 'CAPTCHA solved', result); ``` -------------------------------- ### Parsing Settings from URL Hash Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md This JavaScript code snippet shows how to extract the hash from the current URL and use the SettingsManager to import the settings. ```javascript const hash = window.location.hash.substring(1); // Remove '#' const settings = SettingsManager.import(hash); ``` -------------------------------- ### Check Plan and Credits Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/README.md Checks the current plan, available credits, and quota information for your NopeCHA account. ```APIDOC ## GET /status ### Description Checks the current plan, available credits, and quota information for your NopeCHA account. ### Method GET ### Endpoint https://api.nopecha.com/status ### Parameters #### Query Parameters - **v** (string) - Optional - API version. - **key** (string) - Required - Your NopeCHA API key. ### Response #### Success Response (200) - **plan** (string) - The current subscription plan. - **credit** (number) - The number of remaining credits. - **quota** (object) - Information about the usage quota. - **limit** (number) - The quota limit. - **used** (number) - The amount of quota used. - **duration** (number) - The duration of the current billing cycle in seconds. - **lastreset** (number) - The timestamp of the last quota reset. - **current_period_start** (number) - The start timestamp of the current billing period. - **current_period_end** (number) - The end timestamp of the current billing period. ### Request Example ``` GET /status?key=YOUR_API_KEY ``` ### Response Example ```json { "plan": "free", "credit": 100, "quota": {"limit": 1000, "used": 50}, "duration": 2592000, "lastreset": 1678886400, "current_period_start": 1678886400, "current_period_end": 1681564800 } ``` ``` -------------------------------- ### Project File Structure Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/00-START-HERE.md This code block displays the directory structure of the NopeCHA Browser Extension project, indicating the location of various documentation files. ```tree /output/ ├── 00-START-HERE.md ← YOU ARE HERE ├── README.md ← Navigation & Overview ├── INDEX.md ← Complete Index ├── OVERVIEW.md ← Architecture & Design ├── configuration.md ← Settings Reference ├── types.md ← Type Definitions └── api-reference/ ├── background-api.md ← Background Worker (17 KB) ├── content-script-api.md ← Content Scripts (11 KB) ├── captcha-handlers.md ← CAPTCHA Solvers (12 KB) ├── utilities.md ← Helper Classes (11 KB) └── manifest-reference.md ← Manifest Config (8 KB) ``` -------------------------------- ### General Utilities Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/content-script-api.md Offers general utility functions for string manipulation, data parsing, and ID generation. Use `Util.generate_id` for creating unique identifiers and `Util.pad_left` for formatting numbers. ```javascript static CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' static pad_left(s, char, n) -> string // Pad string on left static capitalize(s) -> string // Capitalize first char static parse_int(s, fallback) -> number // Parse integer with fallback static parse_bool(s, fallback) -> boolean // Parse boolean with fallback static parse_string(s, fallback) -> string // Ensure string with fallback static parse_json(s, fallback) -> object // Parse JSON with fallback static generate_id(n) -> string // Generate random ID of length n ``` ```javascript const id = Util.generate_id(8); // "aB3xYzQp" const padded = Util.pad_left(5, '0', 3); // "005" ``` -------------------------------- ### SettingsManager Encoding Reference Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/configuration.md Defines the serialization and deserialization functions for various extension settings. Each field includes 'parse' for deserialization and 'encode' for serialization. ```javascript { enabled: {parse: Util.parse_bool, encode: encodeURIComponent}, disabled_hosts: {parse: Util.parse_json, encode: e => encodeURIComponent(JSON.stringify(e))}, hcaptcha_auto_open: {parse: Util.parse_bool, encode: encodeURIComponent}, hcaptcha_auto_solve: {parse: Util.parse_bool, encode: encodeURIComponent}, hcaptcha_solve_delay: {parse: Util.parse_bool, encode: encodeURIComponent}, hcaptcha_solve_delay_time: {parse: Util.parse_int, encode: encodeURIComponent}, // ... etc for other CAPTCHA types } ``` -------------------------------- ### Net.fetch Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Fetches a URL and returns the response text. It can be used for making HTTP requests from the background context. ```APIDOC ## Net.fetch({url, options}) ### Description Fetches a URL and returns the response text. Network utilities for making HTTP requests from the background context. ### Method `static async fetch({url, options}={options: {}})` ### Parameters #### Path Parameters - **url** (string) - Required - URL to fetch - **options** (object) - Optional - Fetch options (method, headers, body, etc.) ### Response #### Success Response (200) - **response** (string | null) - Response text, or null if fetch fails ### Request Example ```javascript const html = await BG.exec('Net.fetch', { url: 'https://example.com/api/data' }); const json = await BG.exec('Net.fetch', { url: 'https://api.example.com/submit', options: { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({key: 'value'}) } }); ``` ``` -------------------------------- ### Cache Entry Types Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/types.md Demonstrates how to use different cache entry types (Numeric Counter, String Value, Array, Object) with the Cache.inc, Cache.set, and Cache.append methods. ```APIDOC ## Cache Entry Types ### Numeric Counter ```javascript // Type: number // Usage: for solve counts, retry counts, etc. await BG.exec('Cache.inc', {name: 'count'}); const val = await BG.exec('Cache.get', {name: 'count'}); ``` ### String Value ```javascript // Type: string // Usage: for status strings, messages, etc. await BG.exec('Cache.set', {name: 'status', value: 'solving'}); ``` ### Array ```javascript // Type: array // Usage: for logs, lists of items, etc. await BG.exec('Cache.append', {name: 'log', value: {msg: 'solved'}}); const log = await BG.exec('Cache.get', {name: 'log'}); // Returns: [{msg: 'solved'}, ...] ``` ### Object ```javascript // Type: object // Usage: for complex state await BG.exec('Cache.set', { name: 'captcha_state', value: {type: 'hcaptcha', task: 'dogs', cells: 9} }); ``` ``` -------------------------------- ### SettingsManager.IMPORT_URL Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/utilities.md The base URL used for generating settings import links. ```javascript static IMPORT_URL = 'https://nopecha.com/setup' ``` -------------------------------- ### Firefox Manifest Browser Action (MV2) Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/manifest-reference.md Sets up the browser action for Firefox MV2, defining the popup and title for the extension's button. ```json "browser_action": { "default_popup": "popup.html", "default_title": "NopeCHA: CAPTCHA Solver" } ``` -------------------------------- ### Settings.replace({settings}) Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Replaces the entire settings object with a new one. Use with caution as it overwrites all current settings. ```APIDOC ## Settings.replace({settings}) ### Description Replaces all settings, overwriting the entire settings object. ### Method `BG.exec('Settings.replace', {settings})` ### Parameters #### Request Body - **settings** (object) - Required - Complete settings object ### Returns undefined (void) ### Example ```javascript const newSettings = JSON.parse(JSON.stringify(SettingsManager.DEFAULT)); newSettings.key = 'my-api-key'; await BG.exec('Settings.replace', {settings: newSettings}); ``` ``` -------------------------------- ### Replace All Extension Settings Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Overwrites the entire settings object with a new configuration. Use this when you need to apply a completely new set of settings. ```javascript const newSettings = JSON.parse(JSON.stringify(SettingsManager.DEFAULT)); newSettings.key = 'my-api-key'; await BG.exec('Settings.replace', {settings: newSettings}); ``` -------------------------------- ### Background API - Cache Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/INDEX.md Methods for interacting with the extension's cache. ```APIDOC ## Cache.set({tab_id, name, value, tab_specific}) ### Description Store a value in the cache. ### Method `Cache.set({tab_id, name, value, tab_specific})` ### Parameters - **tab_id** (number) - The ID of the tab to associate the cache entry with. - **name** (string) - The name of the cache entry. - **value** (any) - The value to store. - **tab_specific** (boolean) - Whether the cache entry is specific to the tab (default: false). ``` ```APIDOC ## Cache.get({tab_id, name, tab_specific}) ### Description Retrieve a value from the cache. ### Method `Cache.get({tab_id, name, tab_specific})` ### Parameters - **tab_id** (number) - The ID of the tab to retrieve the cache entry from. - **name** (string) - The name of the cache entry. - **tab_specific** (boolean) - Whether the cache entry is specific to the tab (default: false). ### Response - **value** (any) - The retrieved cache value. ``` ```APIDOC ## Cache.remove({tab_id, name, tab_specific}) ### Description Remove a value from the cache. ### Method `Cache.remove({tab_id, name, tab_specific})` ### Parameters - **tab_id** (number) - The ID of the tab associated with the cache entry. - **name** (string) - The name of the cache entry to remove. - **tab_specific** (boolean) - Whether the cache entry is specific to the tab (default: false). ``` ```APIDOC ## Cache.append({...}) ### Description Append a value to an array stored in the cache. ### Method `Cache.append({...})` ### Parameters - **tab_id** (number) - The ID of the tab. - **name** (string) - The name of the cache entry (must be an array). - **value** (any) - The value to append. - **tab_specific** (boolean) - Whether the cache entry is specific to the tab (default: false). ``` ```APIDOC ## Cache.empty({...}) ### Description Clear an array stored in the cache. ### Method `Cache.empty({...})` ### Parameters - **tab_id** (number) - The ID of the tab. - **name** (string) - The name of the cache entry (must be an array). - **tab_specific** (boolean) - Whether the cache entry is specific to the tab (default: false). ``` ```APIDOC ## Cache.inc({...}) ### Description Increment a counter stored in the cache. ### Method `Cache.inc({...})` ### Parameters - **tab_id** (number) - The ID of the tab. - **name** (string) - The name of the cache entry (must be a number). - **tab_specific** (boolean) - Whether the cache entry is specific to the tab (default: false). ``` ```APIDOC ## Cache.dec({...}) ### Description Decrement a counter stored in the cache. ### Method `Cache.dec({...})` ### Parameters - **tab_id** (number) - The ID of the tab. - **name** (string) - The name of the cache entry (must be a number). - **tab_specific** (boolean) - Whether the cache entry is specific to the tab (default: false). ``` ```APIDOC ## Cache.zero({...}) ### Description Reset a counter stored in the cache to zero. ### Method `Cache.zero({...})` ### Parameters - **tab_id** (number) - The ID of the tab. - **name** (string) - The name of the cache entry (must be a number). - **tab_specific** (boolean) - Whether the cache entry is specific to the tab (default: false). ``` -------------------------------- ### Background API - Icon Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/INDEX.md Control the browser action icon. ```APIDOC ## Icon.set({status}) ### Description Set the state of the browser action icon. ### Method `Icon.set({status})` ### Parameters - **status** (string) - The desired state of the icon (e.g., 'on', 'off'). ``` -------------------------------- ### Browser Utilities Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Utilities for retrieving browser information and logging. ```APIDOC ## Browser.version ### Description Returns the browser platform identifier. ### Method `Browser.version()` ### Parameters None ### Returns - `string` - `"chrome"` or `"firefox"`. ### Example ```javascript const version = await BG.exec('Browser.version'); if (version === 'chrome') { // Chrome-specific code } ``` ``` ```APIDOC ## Browser.log ### Description Logs to the background service worker console. ### Method `Browser.log(...args)` ### Parameters - Any arguments to log. ### Returns - `void` - undefined. ### Example ```javascript await BG.exec('Browser.log', 'Debug message', {key: 'value'}); ``` ``` -------------------------------- ### SettingsManager.import(encoded_hash) Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/utilities.md Parses a URL-encoded settings hash string into a settings object. Missing fields are populated with default values. ```javascript static import(encoded_hash) -> object ``` ```javascript const hash = 'my-key|enabled=true|hcaptcha_solve_delay_time=5000'; const settings = SettingsManager.import(hash); // {key: 'my-key', enabled: true, hcaptcha_solve_delay_time: 5000, ...defaults...} ``` -------------------------------- ### Update Multiple Extension Settings Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Modifies several settings simultaneously by merging new values with existing ones. Ideal for applying multiple configuration changes at once. ```javascript await BG.exec('Settings.update', { settings: { enabled: true, hcaptcha_solve_delay_time: 4000, recaptcha_auto_solve: false } }); ``` -------------------------------- ### Inject.files Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Injects one or more script files into a specific frame within a tab. ```APIDOC ## Inject.files ### Description Injects one or more script files into a specific frame. ### Method `BG.exec('Inject.files', {tab_id, frame_id, files})` ### Parameters #### Path Parameters - **tab_id** (number) - Required - Tab ID - **frame_id** (number) - Required - Frame ID (0 for main frame, >0 for iframes) - **files** (array) - Required - Array of script file paths (e.g., `['/scripts/helper.js']`) ### Request Example ```javascript await BG.exec('Inject.files', { tab_id: 42, frame_id: 0, files: ['/hcaptcha.js', '/locate.js'] }); ``` ### Returns Promise that resolves when scripts are injected ``` -------------------------------- ### RunningAs Enum Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/utilities.md Defines the execution context of the current script, indicating where the code is running (e.g., background, popup, content script, or web). ```APIDOC ## RunningAs Enum Defines the execution context of the current script. ```javascript export class RunningAs { static BACKGROUND = 'BACKGROUND' // Background service worker static POPUP = 'POPUP' // Extension popup static CONTENT = 'CONTENT' // Content script in webpage static WEB = 'WEB' // Standalone script in page } Object.freeze(RunningAs) ``` ``` -------------------------------- ### Inject.func Source: https://github.com/nopechallc/nopecha-extension/blob/main/_autodocs/api-reference/background-api.md Injects and executes a JavaScript function in the main page context of a specified tab. ```APIDOC ## Inject.func ### Description Injects and executes a function in the main page context with given arguments. ### Method `BG.exec('Inject.func', {tab_id, func, args})` ### Parameters #### Path Parameters - **tab_id** (number) - Optional - Tab ID to inject into (defaults to active tab) - **func** (function) - Required - Function to execute (will be stringified) - **args** (array) - Optional - Arguments to pass to the function (defaults to []) ### Request Example ```javascript await BG.exec('Inject.func', { tab_id: 42, func: () => { window.grecaptcha?.reset(); } }); await BG.exec('Inject.func', { tab_id: 42, func: (message) => { console.log('Injected message:', message); }, args: ['Hello from background'] }); ``` ### Returns Promise that resolves when script executes ```