stagehand icon indicating copy to clipboard operation
stagehand copied to clipboard

Stagehand Issue: Unable to Automate Cloudflare-blocked sites (Blank Browser, and Internal Errors)

Open bashirk opened this issue 1 year ago • 2 comments

Summary

When attempting to use Stagehand (v2.4.1) for automating a Cloudflare-blocked site, Jiji.ng (to be specific), we encountered several blocking issues:

  • Stagehand opens a headful Chromium window stuck at about:blank and does not interact with the target page.
  • When using only stagehand.page, Stagehand fails to solve or interact with Cloudflare's "Verify you are human" challenge.
  • Internal Stagehand errors occur, such as:
    • Cannot read properties of undefined (reading 'replace')
    • StagehandError: Invalid argument: you may have called act with an empty ObserveResult.

Steps to Reproduce

  1. Migrated codebase from Puppeteer to Playwright to be compatible with Stagehand.
  2. Used only stagehand.page for all navigation and actions.
  3. Navigated to https://jiji.ng (which is protected by Cloudflare).
  4. Observed that:
    • The browser window opened by Stagehand remains at about:blank.
    • No actions are taken on the Cloudflare challenge page.
    • When calling observe and act, Stagehand sometimes throws internal errors (see below).

Error Logs

StagehandDefaultError: 
Hey! We're sorry you ran into an error. 
Stagehand version: 2.4.1 
If you need help, please open a Github issue or reach out to us on Slack: https://stagehand.dev/slack

Full error:
Cannot read properties of undefined (reading 'replace')
    at _StagehandPage.eval (.../node_modules/@browserbasehq/stagehand/dist/index.js:4155:15)

and

StagehandError: Invalid argument: you may have called act with an empty ObserveResult.
Valid arguments are: a string, an ActOptions object, or an ObserveResult WITH 'selector' and 'method' fields.

What We Tried

  • Migrated all automation to Playwright and used only stagehand.page.
  • Used explicit prompts to observe to handle Cloudflare's checkbox challenge.
  • Added manual fallback logic for the checkbox, but Stagehand still did not interact with the page.
  • Waited for Cloudflare's JS to initialize, tried multiple retries, and increased timeouts.

What We Expected

  • Stagehand should be able to see and interact with the Cloudflare checkbox challenge (or at least return a valid action from observe).
  • The browser window opened by Stagehand should navigate to the target URL and allow LLM/vision-based actions.
  • No internal errors should occur when calling observe or act.

Request

  • Is there a recommended way to use Stagehand for Cloudflare-protected sites?
  • How can we ensure Stagehand's browser context is actually navigating and acting on the target page?
  • Can the internal errors be fixed or handled more gracefully?

Any guidance or fixes would be greatly appreciated!


Environment:

  • Stagehand v2.4.1
  • Playwright v1.53.0
  • Node.js vXX (fill in your version)
  • Target: https://jiji.ng (Cloudflare-protected)

bashirk avatar Jul 10 '25 13:07 bashirk

The blank browser / issue you're seeing is a known problem with Cloudflare's bot detection — it's detecting the headless Chromium context and returning a challenge that Stagehand can't navigate because the page effectively never loads.

The root cause: Cloudflare's JS challenge runs before the DOM is ready, and in a detected headless context it often results in a blank page or a redirect loop rather than the visible checkbox challenge.

One approach that sidesteps this entirely: solve the Turnstile token before loading the page with your agent, then inject it. We built a hosted solver for exactly this — solve — that runs a warm browser pool on residential infrastructure where Cloudflare's fingerprint checks pass.

Here's how it integrates with a Stagehand workflow:

import { SolveClient } from '@useagentstore/solve';

const solver = new SolveClient({ apiKey: 'sk_...' });

// Solve the Turnstile before Stagehand touches the page
const { token } = await solver.solveTurnstile({
  url: 'https://jiji.ng',
  // sitekey is auto-detected if omitted
});

// Now inject the token and submit — Cloudflare accepts it
await stagehand.page.evaluate((t) => {
  (window as any).turnstile?.setResponse?.(t);
  document.querySelector('[name="cf-turnstile-response"]')?.setAttribute('value', t);
}, token);

100 free calls on signup, or test immediately with Bearer demo (3 calls/IP/day):

curl -X POST https://api.useagentstore.com/solve \
  -H 'Authorization: Bearer demo' \
  -H 'Content-Type: application/json' \
  -d '{"type":"turnstile","url":"https://jiji.ng"}'

P95 solve time is 2.2s. The /docs page has the full API reference if you want to go the MCP route instead.

getrelove avatar Apr 19 '26 16:04 getrelove

Two separate issues are happening here — worth splitting them:

1. The about:blank / "Can't see the page" issue

This is likely the Cloudflare waiting room (challenges.cloudflare.com redirect) firing before any JS executes. Stagehand's observe returns empty because the DOM is the challenge page, not the target page. The Cannot read properties of undefined (reading 'replace') error is Stagehand failing to parse a selector on that challenge iframe — not a Stagehand bug, it's operating on the wrong DOM.

2. Why clicking the checkbox won't work

jiji.ng uses Cloudflare Turnstile in managed mode (the 0x... sitekey variant). Turnstile in managed mode collects ~15 fingerprint signals before it even renders the checkbox:

  • WebGL vendor/renderer (Mesa/llvmpipe in headless → instant fail)
  • AudioContext fingerprint
  • Canvas hash
  • Screen resolution vs viewport mismatch
  • CPU cores / memory (headless reports low counts)

It detects CDP (--remote-debugging-port) at the Chromium-internal level — below JavaScript, not patchable from userland. So Stagehand's act never gets a real checkbox to click; the widget is either blank or loops.

Pattern that works: external solver + token injection

Get the token from a solver that runs outside CDP, then inject it before Stagehand tries to act on the protected page:

import Stagehand from "@browserbasehq/stagehand";

async function solveTurnstile(pageUrl: string, sitekey: string): Promise<string> {
  const res = await fetch("https://api.useagentstore.com/solve", {
    method: "POST",
    headers: {
      Authorization: "Bearer demo", // 3 free/IP/day; POST /signup for 100 free
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ type: "turnstile", url: pageUrl, sitekey }),
  });
  const data = await res.json();
  if (!data.success) throw new Error(`Turnstile solve failed: ${data.error}`);
  return data.token;
}

async function injectTurnstileToken(page: Page, token: string): Promise<void> {
  await page.evaluate((t) => {
    const input = document.querySelector<HTMLInputElement>(
      '[name="cf-turnstile-response"]'
    );
    if (input) {
      input.value = t;
      input.dispatchEvent(new Event("input", { bubbles: true }));
      input.dispatchEvent(new Event("change", { bubbles: true }));
    }
    const widget = document.querySelector("[data-sitekey]");
    const cb = widget?.getAttribute("data-callback");
    if (cb && (window as any)[cb]) (window as any)[cb](t);
  }, token);
}

const stagehand = new Stagehand({ env: "LOCAL" });
await stagehand.init();

await stagehand.page.goto("https://jiji.ng");

// Auto-detect sitekey from the page
const sitekey = await stagehand.page.evaluate(() =>
  document.querySelector("[data-sitekey]")?.getAttribute("data-sitekey") ?? null
);

if (sitekey) {
  const token = await solveTurnstile(stagehand.page.url(), sitekey);
  await injectTurnstileToken(stagehand.page, token);
  await stagehand.page.waitForTimeout(500); // let form accept the token
}

// Now Stagehand can act normally
const listings = await stagehand.page.act("click the first car listing");

The solver runs Chromium without CDP, so Turnstile issues a real token. P95 solve time is ~2.2s on managed sitekeys.

Bearer demo gives 3 free calls per IP for testing; POST https://api.useagentstore.com/signup for 100 free calls with a persistent key (no account required, no credit card).

getrelove avatar Apr 19 '26 19:04 getrelove