某些浏览器自动化工作流需要人工干预。登录页面可能需要多因素身份验证,表单可能需要你不想传递给自动化脚本的敏感凭据,或者任务可能过于复杂而无法完全自动化。Human in the Loop 让人类通过 Live View 进入实时浏览器会话,处理自动化无法完成的部分,然后将控制权交还给脚本。
- 身份验证流程:具有 MFA、SSO 或 CAPTCHA 的登录页面,无法以编程方式绕过
- 敏感数据输入:需要凭据或个人信息的表单,你不想传递给自动化脚本
- 复杂交互:过于困难或不值得完全自动化的一次性任务,例如配置仪表板或批准工作流
- 验证步骤:在脚本继续之前确认订单、审查生成的内容或批准操作
Human in the Loop 适用于任何 Browser Session,并提供两种人工介入方式:
脚本使用 Cloudflare CDP 命令正式请求人工介入并等待完成:
- 自动化脚本遇到需要人工输入的场景。
- 脚本订阅
Cloudflare.handoffComplete事件。 - 脚本发送
Cloudflare.getLiveView,mode 为tab,并将返回的 URL 与人工操作员共享。 - 脚本发送
Cloudflare.handoffCDP 命令并附带给人工操作员的说明,然后等待Cloudflare.handoffComplete。 - 操作员打开 Live View(/browser-run/features/live-view/)URL,完成所需操作,然后选择 "Done" 或 "Failed"。
- 当人工将交接标记为完成或交接超时时,
Cloudflare.handoffComplete会触发。 - 自动化在获知介入是否成功后继续执行。
完整代码示例请参阅示例:结构化交接。
对于更简单的用例,你可以手动管理交接:
- 自动化脚本前往需要人工输入的页面。
- 脚本从会话的 target 列表中获取 Live View URL,并与人工操作员共享。
- 人工操作员打开 Live View URL 并完成所需操作。
- 自动化脚本通过轮询页面元素或等待导航事件来检测完成。
完整代码示例请参阅示例:手动检测。
Browser Run 在标准 Chrome DevTools Protocol (CDP) ↗ 之上扩展了 Cloudflare.* 命名空间下的 Cloudflare 特定命令。这些命令仅在连接到 Browser Run 会话时可用,并提供标准 CDP 规范中不存在的能力,例如请求人工介入、生成 Live View URL 以及跟踪交接状态。
你通过 CDP 会话发送这些命令的方式与发送任何标准 CDP 命令相同。完整参数和返回类型详情请参阅协议参考。
为当前页面请求人工介入。target 会从 CDP 会话自动解析。
const cdp = await page.createCDPSession();
const { handoffId } = await cdp.send("Cloudflare.handoff", {
// targetId will automatically be resolved from the CDP session
instructions: "Please log in",
timeout: 1800000, // optional, max 30 minutes, if undefined handoff will have no timeout
});当你的浏览器有多个页面时,为特定 target 请求交接:
// Get all targets
const { targetInfos } = await cdp.send("Target.getTargets");
// Find a specific target (for example, a page with a specific URL)
const target = targetInfos.find(
(t) => t.type === "page" && t.url.includes("example.com"),
);
if (!target) {
throw new Error("Target not found");
}
// Request handoff for the selected target
const { handoffId } = await cdp.send("Cloudflare.handoff", {
targetId: target.targetId,
instructions: "Please complete the CAPTCHA on this page",
});在人工介入完成或超时时发出。监听此事件,以便在人工完成后恢复自动化。
cdp.once("Cloudflare.handoffComplete", (result) => {
if (result.success) {
console.log("Handoff completed successfully");
} else {
console.log(`Handoff failed: ${result.reason}`);
}
});检查当前页面是否有正在进行的交接。
const state = await cdp.send("Cloudflare.getHandoffState", {
targetId, // optional, defaults to the current page
});
if (state.active) {
console.log(
`Handoff ${state.handoffId} has been active for ${state.durationMs}ms`,
);
}为浏览器会话生成 Live View URL。将其与 Cloudflare.handoff 一起使用,以便人工操作员访问实时浏览器。
const { devtoolsFrontendUrl } = await cdp.send("Cloudflare.getLiveView", {
targetId, // optional, defaults to the current page
mode: "tab", // optional, one of "tab", "full", or "devtools" (default)
expiresInMs: 300000, // optional, default 5 minutes, max 1 hour
});
console.log(`Live View URL: ${devtoolsFrontendUrl}`);此示例演示结构化交接流程。脚本使用 Cloudflare CDP 命令请求人工介入,并在恢复之前等待完成事件:
import puppeteer, { type HandoffCompleteResponse } from "@cloudflare/puppeteer";
const ACCOUNT_ID = "<your-account-id>";
const API_TOKEN = "<your-api-token>";
// Connect to Browser Run
const browser = await puppeteer.connect({
browserWSEndpoint: `wss://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/browser-run/devtools/browser?keep_alive=600000`,
headers: { Authorization: `Bearer ${API_TOKEN}` },
});
// If using a Cloudflare Worker, you can use: await puppeteer.launch(env.MYBROWSER)
const page = await browser.newPage();
await page.goto("https://github.com/login");
// Create a CDP session to send Browser Run commands
const cdp = await page.createCDPSession();
// Get the Live View URL for the human operator
const { devtoolsFrontendUrl } = await cdp.send("Cloudflare.getLiveView", {
mode: "tab", // required, only "tab" supports handoff
expiresInMs: 300000, // optional, default is 5 minutes
});
// Share the Live View URL with the human operator (for example, send it via Slack, email, or display it in a UI)
console.log(`Human input needed. Open this URL: ${devtoolsFrontendUrl}`);
// Set up completion listener before initiating handoff
const handoffCompletePromise = new Promise<HandoffCompleteResponse>((resolve) => {
cdp.once("Cloudflare.handoffComplete", (event) => resolve(event as HandoffCompleteResponse));
});
// Request human intervention with specific instructions
const { handoffId } = await cdp.send("Cloudflare.handoff", {
instructions: "Please log in with your GitHub credentials",
timeout: 600_000, // 10 minute timeout
});
console.log(`Human intervention requested (ID: ${handoffId})`);
// Wait for human to complete the task
const result = await handoffCompletePromise;
if (result.success) {
console.log("Login successful, continuing automation...");
// Continue with your automation...
await page.goto("https://github.com/settings/profile");
} else {
console.error(`Human intervention failed: ${result.reason}`);
}
await browser.close();import type { HandoffCompleteResponse } from "@cloudflare/playwright";
import { chromium } from "playwright-core";
// If using a Cloudflare Worker, import { launch } from "@cloudflare/playwright" and use launch(env.MYBROWSER) instead.
const ACCOUNT_ID = "<your-account-id>";
const API_TOKEN = "<your-api-token>";
// Connect to Browser Run
const browser = await chromium.connectOverCDP(
`wss://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/browser-run/devtools/browser?keep_alive=600000`,
{ headers: { Authorization: `Bearer ${API_TOKEN}` } },
);
const context = browser.contexts()[0] ?? (await browser.newContext());
const page = await context.newPage();
await page.goto("https://github.com/login");
// Create a CDP session to send Browser Run commands
const cdp = await context.newCDPSession(page);
// Get the Live View URL for the human operator
const { devtoolsFrontendUrl } = await cdp.send("Cloudflare.getLiveView", {
mode: "tab", // required, only "tab" supports handoff
expiresInMs: 300000, // optional, default is 5 minutes
});
// Share the Live View URL with the human operator (for example, send it via Slack, email, or display it in a UI)
console.log(`Human input needed. Open this URL: ${devtoolsFrontendUrl}`);
// Set up completion listener before initiating handoff.
// `cdp.once` for Cloudflare.* events needs a call-site cast because
// Playwright's `CDPSession.on/once/off` are declared as arrow-property
// signatures that TypeScript can't merge overloads into.
const handoffCompletePromise = new Promise<HandoffCompleteResponse>((resolve) => {
(cdp.once as (event: string, listener: (p: HandoffCompleteResponse) => void) => void)(
"Cloudflare.handoffComplete",
resolve,
);
});
// Request human intervention with specific instructions
const { handoffId } = await cdp.send("Cloudflare.handoff", {
instructions: "Please log in with your GitHub credentials",
timeout: 600000, // 10 minute timeout
});
console.log(`Human intervention requested (ID: ${handoffId})`);
// Wait for human to complete the task
const result = await handoffCompletePromise;
if (result.success) {
console.log("Login successful, continuing automation...");
// Continue with your automation...
await page.goto("https://github.com/settings/profile");
} else {
console.error(`Human intervention failed: ${result.reason}`);
}
await browser.close();此示例使用共享 Live View URL 并轮询完成状态的手动方法:
import puppeteer from "@cloudflare/puppeteer";
const ACCOUNT_ID = "<your-account-id>";
const API_TOKEN = "<your-api-token>";
// Connect to Browser Run
const browser = await puppeteer.connect({
browserWSEndpoint: `wss://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/browser-run/devtools/browser?keep_alive=600000`,
headers: { Authorization: `Bearer ${API_TOKEN}` },
});
const page = await browser.newPage();
await page.goto("https://github.com/login");
// Create CDP session and get Live View URL
const cdp = await page.createCDPSession();
const { devtoolsFrontendUrl } = await cdp.send("Cloudflare.getLiveView", {
expiresInMs: 300000, // 5 minutes
});
// Share the Live View URL with the human operator (for example, send it via Slack, email, or display it in a UI)
console.log(`Human input needed. Open this URL: ${devtoolsFrontendUrl}`);
// Wait until GitHub reports a non-empty `<meta name="user-login">` in the
// page head. This meta tag is always present, but its content is empty
// for logged-out viewers and set to the username after login. Waiting for
// content to be populated is a reliable "human finished logging in" signal.
await page.waitForFunction(
() =>
document
.querySelector('meta[name="user-login"]')
?.getAttribute("content") !== "",
{ timeout: 300000 },
);
// Login complete, continue automation
console.log("Login complete. Continuing automation...");
// Verify we're logged in and read the username
const username = await page.$eval('meta[name="user-login"]', (el) =>
el.getAttribute("content"),
);
console.log(`Logged in as: ${username}`);
await page.goto("https://github.com/");
await browser.close();import type { GetLiveViewResponse } from "@cloudflare/playwright";
import { chromium } from "playwright-core";
// If using a Cloudflare Worker, import { launch } from "@cloudflare/playwright" and use launch(env.MYBROWSER) instead.
const ACCOUNT_ID = "<your-account-id>";
const API_TOKEN = "<your-api-token>";
// Connect to Browser Run
const browser = await chromium.connectOverCDP(
`wss://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/browser-run/devtools/browser?keep_alive=600000`,
{ headers: { Authorization: `Bearer ${API_TOKEN}` } },
);
const context = browser.contexts()[0] ?? (await browser.newContext());
const page = await context.newPage();
await page.goto("https://github.com/login");
// Create CDP session and get Live View URL
const cdp = await context.newCDPSession(page);
const { devtoolsFrontendUrl }: GetLiveViewResponse = await cdp.send(
"Cloudflare.getLiveView",
{ expiresInMs: 300000 }, // 5 minutes
);
// Share the Live View URL with the human operator (for example, send it via Slack, email, or display it in a UI)
console.log(`Human input needed. Open this URL: ${devtoolsFrontendUrl}`);
// Wait until GitHub reports a non-empty `<meta name="user-login">` in the
// page head. This meta tag is always present, but its content is empty
// for logged-out viewers and set to the username after login. Waiting for
// content to be populated is a reliable "human finished logging in" signal.
await page.waitForFunction(
() =>
document
.querySelector('meta[name="user-login"]')
?.getAttribute("content") !== "",
null,
{ timeout: 300000 },
);
// Login complete, continue automation
console.log("Login complete. Continuing automation...");
// Verify we're logged in and read the username
const username = await page.$eval('meta[name="user-login"]', (el) =>
el.getAttribute("content"),
);
console.log(`Logged in as: ${username}`);
await page.goto("https://github.com/");
await browser.close();向人工操作员提供具体、可执行的指导:
// Good: specific and actionable
await cdp.send("Cloudflare.handoff", {
instructions:
"Review the items in the cart and if approved for checkout, click 'Done'. Otherwise, click 'Failed' and provide a reason.",
});根据任务复杂度匹配超时时长:
// Quick tasks — 2-3 minutes
await cdp.send("Cloudflare.handoff", {
instructions: "Click the 'I agree' checkbox and submit",
timeout: 120000,
});
// Complex tasks - 10-15 minutes
await cdp.send("Cloudflare.handoff", {
instructions: "Complete the multi-page application form with test data",
timeout: 900000,
});在需要时检查交接状态:
// Check if a handoff is already active before requesting a new one
const currentState = await cdp.send("Cloudflare.getHandoffState");
if (currentState.active) {
console.log(`Handoff already active: ${currentState.handoffId}`);
// Wait for current handoff or handle appropriately
} else {
// Safe to start new handoff
await cdp.send("Cloudflare.handoff", {
/* ... */
});
}