Electron CAPTCHA: Solve Turnstile From the Main Process

To solve a CAPTCHA from an Electron app, keep the work in the main process. Load the page in a BrowserWindow, read the sitekey with webContents.executeJavaScript, ask CapSkip for a token with the capskip Node SDK, switch the window to the User-Agent the solver reports, write the token into the hidden field and submit the form. This electron captcha guide is for the developer who has to pass a Turnstile widget from inside an Electron app, not add one to their own site. The renderer asks for the job over IPC and never sees the API key. Each token comes from the CapSkip Turnstile solver running on a Windows PC you own.
What you need
- A Windows PC with CapSkip installed as the setup guide describes and running in Local mode, which listens on 127.0.0.1:8080.
- Node.js 22.12 or later for npm, the floor the electron package declares. The capskip package declares Node.js 18, which the Node.js inside Electron 45.3.0 clears: it reported 24.22.2. In my run the first start spent 21.9 seconds downloading the Electron program, which npm install did not fetch.
- A page with a Turnstile widget that you may automate.
- An address for CapSkip that suits where the app runs. Local mode serves only its own PC, and Server mode listens on your network or public IP, which a shipped app needs (see the last section).
I chose Turnstile because its widget keeps the token in a plain hidden input, and its result carries the User-Agent the solver used, while an Electron page loads with a different one. That clash is the part of this job that belongs to Electron.
Everything ran on Windows 11 with Electron 45.3.0 (Chrome 156.0.8078.96) and capskip 1.7.0, against two mocks I wrote: one plays CapSkip and one plays a contact page with a Turnstile-shaped widget. The token text and every site rule are mine, and the real CapSkip app received no task. A wrapper started the same main.js, hid each window as it opened and clicked the button from script; one run with visible windows agreed. I never packaged the app.
Step 1: two windows, a preload and the IPC bridge
Create an empty folder and run these three commands. The last one makes npm start the project from main.js.
# npm install electron capskip npm init -y npm install electron capskip npm pkg set main=main.js
The app needs two windows. One shows your own interface and gets a preload script. The other loads the page with the CAPTCHA and gets nothing, so a script on that page has no bridge to your main process. I set contextIsolation, nodeIntegration and sandbox explicitly, but a window with no webPreferences in Electron 45.3.0 reported the same values, and the Electron security guide dates those defaults to versions 12, 5 and 20.
// main.js
const { app, BrowserWindow, ipcMain } = require("electron");
const { once } = require("node:events");
const path = require("node:path");
const { CapSkip } = require("capskip");
// The page that shows the Turnstile widget.
const SITE_URL = process.env.SITE_URL || "https://example.com/contact";
// The only place that knows the host and the key. Local mode by default.
const solver = new CapSkip({
host: process.env.CAPSKIP_HOST || "127.0.0.1",
port: Number(process.env.CAPSKIP_PORT || 8080),
apiKey: process.env.CAPSKIP_API_KEY || "capskip",
});
let ui;
let site;
let busy = false;
// The page with the CAPTCHA: no preload, so nothing is exposed to it.
function createSite() {
return new BrowserWindow({
width: 900,
height: 700,
webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },
});
}
app.whenReady().then(() => {
// Your own interface: the only window that gets the preload script.
ui = new BrowserWindow({
width: 480,
height: 320,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
});
ui.loadFile("index.html");
site = createSite();
});
app.on("window-all-closed", () => app.quit());CapSkip is built once, here, and its host, port and key come from environment variables that you read yourself, because the SDK reads none. The preload exposes a single function, never the whole ipcRenderer, and invoke resolves with whatever the main process handler returns.
// preload.js
const { contextBridge, ipcRenderer } = require("electron");
// Expose one narrow function, never ipcRenderer itself.
contextBridge.exposeInMainWorld("captcha", {
send: (email) => ipcRenderer.invoke("captcha:send", email),
});The interface script sits in a separate file, so its own Content-Security-Policy can allow scripts from self only, as the security guide advises.
<!-- index.html --> <!doctype html> <meta charset="utf-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'"> <title>Send with CAPTCHA</title> <input id="email" value="[email protected]"> <button id="go">Solve and send</button> <pre id="out"></pre> <script src="renderer.js"></script>
// renderer.js
const go = document.getElementById("go");
const out = document.getElementById("out");
go.addEventListener("click", async () => {
go.disabled = true;
out.textContent = "Solving";
const reply = await window.captcha.send(document.getElementById("email").value);
out.textContent = JSON.stringify(reply, null, 2);
go.disabled = false;
});In both windows require and process were undefined; window.captcha held one key, send, in the interface window and was undefined in the page window; and the API key appeared in neither page’s HTML. A probe window that had the same preload but showed another page got a refused reply from the handler’s sender check, which the Electron security guide asks for.
Step 2: the handler that solves and submits
Paste this below the first part of main.js. It loads the page, reads the sitekey from the widget’s data-sitekey attribute, calls solver.turnstile, adopts the reported User-Agent, fills the form and waits for the page that comes back.
// main.js, continued below the first part
// Read the sitekey from the page, solve, set the User-Agent, fill, submit.
async function solveAndSend(email) {
// The user may have closed the page window since the last job.
if (!site || site.isDestroyed()) site = createSite();
await site.loadURL(SITE_URL);
const web = site.webContents;
const sitekey = await web.executeJavaScript(
`document.querySelector("[data-sitekey]")?.dataset.sitekey ?? null`
);
if (!sitekey) return { ok: false, error: "no widget on the page" };
// Turnstile polls on defaultTimeout; this call is capped at 60 seconds.
const solved = await solver.turnstile(sitekey, web.getURL(), { timeout: 60 });
if (web.isDestroyed()) return { ok: false, error: "window closed" };
// Submit with the User-Agent the token was earned with.
if (solved.userAgent) web.setUserAgent(solved.userAgent);
// JSON.stringify keeps a quote in a value from breaking out of the string.
const fill = `(() => {
const form = document.querySelector("form");
form.elements["email"].value = ${JSON.stringify(email)};
let field = form.elements["cf-turnstile-response"];
if (!field) {
field = Object.assign(document.createElement("input"), { type: "hidden", name: "cf-turnstile-response" });
form.appendChild(field);
}
field.value = ${JSON.stringify(solved.code)};
form.requestSubmit();
})()`;
const loaded = once(web, "did-finish-load");
await web.executeJavaScript(fill);
await loaded;
const page = await web.executeJavaScript("document.body.innerText");
return { ok: true, page: page.trim().slice(0, 80) };
}
ipcMain.handle("captcha:send", async (event, email) => {
if (event.sender !== ui.webContents) return { ok: false, error: "refused" };
if (typeof email !== "string" || email.length > 200) {
return { ok: false, error: "bad email" };
}
if (busy) return { ok: false, error: "busy" };
busy = true;
try {
return await solveAndSend(email);
} catch (err) {
// An Error thrown here reaches the renderer as a message only.
return { ok: false, error: err.constructor.name, message: err.message };
} finally {
busy = false;
}
});Four details matter. First, in 1.7.0 a Turnstile answer held captchaId, code and userAgent and no token field, so the token is code. Second, the reply says ok when the form was submitted, not when the site accepted the token: with the User-Agent step skipped, my mock answered ok to the app and Verification failed on the page, so look for your own site’s success text. Third, Cloudflare’s rendering guide says implicit rendering adds an invisible input named cf-turnstile-response, and that tokens expire after 300 seconds and validate once. If your page runs a callback when the widget finishes, the CapSkip API docs advise running it with the token; I did not test that. I loaded Cloudflare’s real widget script once in a hidden window, with a sitekey Cloudflare publishes for testing, and the input appeared about 2.5 seconds after load, so the code creates the field when it is missing. I submitted that token nowhere and did not test whether the widget overwrites a value you set. Fourth, JSON.stringify builds the values into the script, and an email holding quotes and a backslash reached my mock unchanged.
Time limits and a closed window
Turnstile polls on the client’s default timeout of 120 seconds, not the longer reCAPTCHA one: with defaultTimeout 5 and recaptchaTimeout 300, a mock that never answered ended in TimeoutException after 7.8 seconds. The timeout option is per call, in seconds, and I set 60. The SDK checks the deadline only when the next poll is due, so a mock that never answered took 63.0 seconds from click to reply. ipcRenderer.invoke has no timeout of its own: a handler that never returned left the call pending when I stopped watching after 20 seconds. The SDK timeout is your only limit.
The SDK cannot be cancelled. When I closed the page window 1.5 seconds into a 4 second mock solve, the SDK kept polling and the reply came at 7.9 seconds. Without the isDestroyed check, setUserAgent threw TypeError: Object has been destroyed, and without createSite every later click failed the same way; with both, the next click opened a new page window and succeeded. A second click during a solve got the busy reply, since one page window cannot serve two jobs.
An Error thrown inside a handler reaches the renderer as a message only: my probe threw MyErr with a code property, and the renderer saw a plain Error. So the handler catches everything and returns an object that keeps the SDK exception’s class name and message.
Step 3: what the page’s Content-Security-Policy blocks
The Electron docs for executeJavaScript do not mention a Content-Security-Policy, so I tested it. I loaded the mock page with no policy and with a script-src self policy, and ran the same probes in the main world.
| Probe | No policy | Policy script-src self |
|---|---|---|
| Inline script written in the page’s own HTML | Ran | Blocked |
| Script file from the page’s own origin | Ran | Ran |
| executeJavaScript setting the hidden input | Worked | Worked |
| Calling eval() or new Function() inside the executed code | Worked | EvalError |
| A script element with inline text that the executed code adds | Ran | Blocked |
| eval() in executeJavaScriptInIsolatedWorld | Worked | Worked |
The code you hand to executeJavaScript runs, but the policy still applies to anything it builds from strings. Set properties and call existing functions, and the policy has no say. The full flow from Step 2 passed against the script-src page, and a default-src none policy, which also blocked the page’s own script file, still let the hidden input be set.
Step 4: the User-Agent the page loads with
An Electron window identifies itself with an Electron token: my mock saw Chrome/156.0.8078.96 Electron/45.3.0. The CapSkip API docs say to send the solver’s User-Agent when you submit a Turnstile token, and the Node SDK does not let you choose it: userAgent and useragent both raised ValidationException with Unsupported parameters for Turnstile. The handler calls webContents.setUserAgent after the page has loaded; my mock recorded these results for five ways of setting it.
| Way to set it | navigator.userAgent | Request header |
|---|---|---|
| webContents.setUserAgent after the page loaded | Changed at once, no reload | Solver’s on the next form submission |
| webContents.setUserAgent before loadURL | Solver’s | Solver’s on the page load and the submission |
| session.setUserAgent on a custom session, or the userAgent option of loadURL | Solver’s | Solver’s on both |
| A webRequest onBeforeSendHeaders hook | Still the Electron string | Solver’s on both |
The hook is the odd one out: a page script that reads navigator.userAgent still sees Electron while the server sees something else. The app learns the User-Agent only once the page is open, so the after-load call fits. None of my requests carried a sec-ch-ua header, and after setUserAgent the navigator.userAgentData.brands list still named Chromium 156, so the two disagree. Chromium added Referer and Origin to the form submission itself. The User-Agent check is my mock’s rule: I tested no real site, so whether one compares the two is untested.
Run it, and Server mode for a shipped app
Set the page address, then start the app. The two commented lines are for Server mode only; leave them alone while CapSkip runs on the same PC.
# Run from the project folder in PowerShell $env:SITE_URL = "https://example.com/contact" # Server mode only: another PC runs CapSkip # $env:CAPSKIP_HOST = "192.168.1.50" # $env:CAPSKIP_API_KEY = "YOUR_API_KEY" npx electron .
An app you ship cannot count on 127.0.0.1 holding a CapSkip. Either each user runs CapSkip in Local mode on their own PC and the code stays as it is, or you run CapSkip on a Windows machine you control in Server mode, where it listens on your network or a public IP, and CAPSKIP_HOST names that machine. CAPSKIP_PORT does the same for a port other than 8080. The connection settings hold the switch, the setup guide says Server mode requires CapSkip to run as administrator, and a static address keeps the app pointed at the same place.
Three cautions follow. CapSkip opens its port to every address when Server mode starts, so to keep it to the machines you expect, add a Windows Firewall block rule for the others, and turn on API Key Validation. The SDK builds an http address with no TLS option, so beyond a LAN or a VPN the key travels in clear text. And a key inside an app you distribute can be read by whoever runs it, so treat it as public. The last two are my reading of the SDK source, not a test.
Common errors
Rows marked mock are what my mock returned through the real SDK; the rest follow the CapSkip docs.
| Reply from the handler | Cause | Fix |
|---|---|---|
| ApiException with ERROR_KEY_DOES_NOT_EXIST (mock) | API Key Validation is on and the key sent is wrong. With no CAPSKIP_API_KEY the SDK sends capskip | Set CAPSKIP_API_KEY |
| NetworkException with connect ECONNREFUSED (mock port) | Nothing listens on that host and port | Start CapSkip, or fix CAPSKIP_HOST and the port |
| TimeoutException with timeout 60 exceeded (mock) | No token within the call timeout; the reply came at 63.0 seconds | Open the CapSkip Monitor, then retry |
| ApiException whose message contains ERROR_CAPTCHA_UNSOLVABLE | The challenge was not passed. The SDK throws the raw reply text; I did not check the real poll error body | Retry with a new task |
| ok true, but the page says the check failed | The form went out; the site refused the token, often a User-Agent or age mismatch | Read the page text, and ask for a fresh token |
| error busy, window closed, no widget on the page | This handler’s own guards | Wait, click again (a new page window opens), or check the page address |
FAQ
Why not call CapSkip from the renderer?
A sandboxed renderer has no require, so the Node SDK cannot load there, and a renderer that held your key would show it to every script it loads. In the main process the key stays in one module.
Can the CapSkip side run on a server instead of the user’s PC?
Yes, through Server mode, as described above. Only CAPSKIP_HOST changes, and the app code stays the same.
An Electron app that needs to get past a CAPTCHA only has to ask the right process: the main one calls CapSkip, the renderer shows the result, and the User-Agent gets switched before the form goes out. For the plain Node.js version without a browser shell, see the Turnstile in Node.js guide. Because CapSkip is a captcha bypass tool that runs on your own PC, retrying a refused token costs nothing extra.
