Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 | /**
* Basic Operation Templates for Browser Hand
*
* Contains fundamental browser operations: navigate, screenshot, form filling, clicking.
*/
import type { TaskTemplate, ExecutionContext } from './types';
// ============================================================================
// Template: Navigate and Screenshot
// ============================================================================
const navigateScreenshotTemplate: TaskTemplate = {
id: 'basic_navigate_screenshot',
name: '打开网页并截图',
description: '访问指定 URL 并截取页面快照',
category: 'basic',
icon: 'Camera',
params: [
{
key: 'url',
label: '网页地址',
type: 'url',
required: true,
placeholder: 'https://example.com',
description: '要访问的网页 URL',
},
{
key: 'waitTime',
label: '等待时间 (毫秒)',
type: 'number',
required: false,
default: 2000,
min: 0,
max: 30000,
description: '页面加载后等待的时间',
},
{
key: 'waitFor',
label: '等待元素',
type: 'text',
required: false,
placeholder: '.main-content',
description: '等待特定元素出现后再截图(CSS 选择器)',
},
],
execute: async (params, context: ExecutionContext) => {
const { browser, onProgress, onLog } = context;
const url = params.url as string;
const waitTime = (params.waitTime as number) ?? 2000;
const waitFor = params.waitFor as string | undefined;
onProgress('正在创建浏览器会话...', 0);
onLog('info', `准备访问: ${url}`);
// Navigate to URL
onProgress('正在导航到页面...', 20);
const navResult = await browser.goto(url);
onLog('info', `页面标题: ${navResult.title}`);
// Wait for page to load
if (waitFor) {
onProgress('等待页面元素加载...', 40);
onLog('action', `等待元素: ${waitFor}`);
await browser.wait(waitFor, 10000);
} else if (waitTime > 0) {
onProgress('等待页面加载...', 40);
await new Promise((resolve) => setTimeout(resolve, waitTime));
}
// Take screenshot
onProgress('正在截取页面快照...', 80);
const screenshot = await browser.screenshot();
onLog('action', '截图完成', { size: screenshot.base64.length });
onProgress('完成', 100);
return {
url: await browser.url(),
title: await browser.title(),
screenshot: screenshot.base64,
format: screenshot.format,
};
},
};
// ============================================================================
// Template: Fill Form
// ============================================================================
const fillFormTemplate: TaskTemplate = {
id: 'basic_fill_form',
name: '填写表单',
description: '填写网页表单并可选提交',
category: 'basic',
icon: 'FileText',
params: [
{
key: 'url',
label: '网页地址',
type: 'url',
required: true,
placeholder: 'https://example.com/form',
},
{
key: 'fields',
label: '表单字段',
type: 'json',
required: true,
default: [],
description: 'JSON 数组,每项包含 selector 和 value',
placeholder: '[{"selector": "input[name=\\"email\\"]", "value": "test@example.com"}]',
},
{
key: 'submitSelector',
label: '提交按钮选择器',
type: 'text',
required: false,
placeholder: 'button[type="submit"]',
description: '填写完成后点击此按钮提交',
},
{
key: 'waitForNavigation',
label: '等待页面跳转',
type: 'boolean',
required: false,
default: false,
description: '提交后等待新页面加载完成',
},
],
execute: async (params, context: ExecutionContext) => {
const { browser, onProgress, onLog } = context;
const url = params.url as string;
const fields = params.fields as Array<{ selector: string; value: string }>;
const submitSelector = params.submitSelector as string | undefined;
const waitForNavigation = params.waitForNavigation as boolean;
onProgress('正在导航到页面...', 0);
onLog('info', `访问: ${url}`);
await browser.goto(url);
onProgress('正在填写表单...', 30);
const totalFields = fields.length;
for (let i = 0; i < fields.length; i++) {
const field = fields[i];
const progress = 30 + Math.floor((i / totalFields) * 40);
onProgress(`正在填写字段 ${i + 1}/${totalFields}...`, progress);
onLog('action', `填写: ${field.selector}`, { value: field.value });
try {
await browser.wait(field.selector, 5000);
await browser.type(field.selector, field.value, true);
} catch (error) {
onLog('warn', `字段填写失败: ${field.selector}`, {
error: String(error),
});
}
}
let result = {
url: await browser.url(),
fieldsFilled: fields.length,
submitted: false,
};
if (submitSelector) {
onProgress('正在提交表单...', 80);
onLog('action', `点击提交: ${submitSelector}`);
try {
await browser.click(submitSelector);
result.submitted = true;
if (waitForNavigation) {
onProgress('等待页面跳转...', 90);
await new Promise((resolve) => setTimeout(resolve, 2000));
}
} catch (error) {
onLog('error', `提交失败: ${submitSelector}`, {
error: String(error),
});
}
}
onProgress('完成', 100);
return result;
},
};
// ============================================================================
// Template: Click and Navigate
// ============================================================================
const clickNavigateTemplate: TaskTemplate = {
id: 'basic_click_navigate',
name: '点击导航',
description: '点击页面元素并等待导航',
category: 'basic',
icon: 'MousePointerClick',
params: [
{
key: 'url',
label: '起始页面',
type: 'url',
required: true,
placeholder: 'https://example.com',
},
{
key: 'selector',
label: '点击目标',
type: 'text',
required: true,
placeholder: 'a.link-to-page',
description: '要点击的元素的 CSS 选择器',
},
{
key: 'waitAfter',
label: '等待时间 (毫秒)',
type: 'number',
required: false,
default: 2000,
description: '点击后等待的时间',
},
{
key: 'takeScreenshot',
label: '截图结果',
type: 'boolean',
required: false,
default: true,
description: '点击后是否截图',
},
],
execute: async (params, context: ExecutionContext) => {
const { browser, onProgress, onLog } = context;
const url = params.url as string;
const selector = params.selector as string;
const waitAfter = (params.waitAfter as number) ?? 2000;
const takeScreenshot = params.takeScreenshot as boolean;
onProgress('正在导航到起始页面...', 0);
onLog('info', `访问: ${url}`);
await browser.goto(url);
onProgress('正在查找点击目标...', 30);
onLog('action', `等待元素: ${selector}`);
await browser.wait(selector, 10000);
onProgress('正在点击...', 50);
onLog('action', `点击: ${selector}`);
await browser.click(selector);
onProgress('等待导航完成...', 70);
await new Promise((resolve) => setTimeout(resolve, waitAfter));
const result: Record<string, unknown> = {
fromUrl: url,
toUrl: await browser.url(),
title: await browser.title(),
};
if (takeScreenshot) {
onProgress('正在截图...', 90);
const screenshot = await browser.screenshot();
result.screenshot = screenshot.base64;
onLog('action', '截图完成');
}
onProgress('完成', 100);
return result;
},
};
// ============================================================================
// Template: Get Page Info
// ============================================================================
const getPageInfoTemplate: TaskTemplate = {
id: 'basic_get_page_info',
name: '获取页面信息',
description: '获取页面标题、URL 和基本信息',
category: 'basic',
icon: 'Info',
params: [
{
key: 'url',
label: '网页地址',
type: 'url',
required: true,
placeholder: 'https://example.com',
},
{
key: 'selectors',
label: '额外选择器',
type: 'textarea',
required: false,
placeholder: '.title\n.description\n.price',
description: '要提取文本的 CSS 选择器(每行一个)',
},
],
execute: async (params, context: ExecutionContext) => {
const { browser, onProgress, onLog } = context;
const url = params.url as string;
const selectorsText = params.selectors as string | undefined;
const selectors = selectorsText
? selectorsText.split('\n').map((s) => s.trim()).filter(Boolean)
: [];
onProgress('正在导航到页面...', 0);
onLog('info', `访问: ${url}`);
await browser.goto(url);
onProgress('正在获取页面信息...', 50);
const result: Record<string, unknown> = {
url: await browser.url(),
title: await browser.title(),
};
if (selectors.length > 0) {
onProgress('正在提取元素文本...', 70);
const extracted: Record<string, string> = {};
for (const selector of selectors) {
try {
const text = await browser.eval(`
(selector) => {
const el = document.querySelector(selector);
return el ? el.textContent?.trim() : null;
}
`, [selector]);
if (text) {
extracted[selector] = text as string;
onLog('info', `提取: ${selector}`, { text });
}
} catch (error) {
onLog('warn', `提取失败: ${selector}`);
}
}
result.extracted = extracted;
}
onProgress('完成', 100);
return result;
},
};
// ============================================================================
// Template: Execute JavaScript
// ============================================================================
const executeJsTemplate: TaskTemplate = {
id: 'basic_execute_js',
name: '执行 JavaScript',
description: '在页面上执行自定义 JavaScript 代码',
category: 'basic',
icon: 'Code',
params: [
{
key: 'url',
label: '网页地址',
type: 'url',
required: true,
placeholder: 'https://example.com',
},
{
key: 'script',
label: 'JavaScript 代码',
type: 'textarea',
required: true,
placeholder: 'return document.title;',
description: '要执行的 JavaScript 代码',
},
],
execute: async (params, context: ExecutionContext) => {
const { browser, onProgress, onLog } = context;
const url = params.url as string;
const script = params.script as string;
onProgress('正在导航到页面...', 0);
onLog('info', `访问: ${url}`);
await browser.goto(url);
onProgress('正在执行 JavaScript...', 50);
onLog('action', '执行脚本', { script: script.substring(0, 100) });
try {
const result = await browser.eval(script);
onLog('info', '执行成功', { result: JSON.stringify(result).substring(0, 200) });
onProgress('完成', 100);
return { success: true, result };
} catch (error) {
onLog('error', `执行失败: ${error}`);
onProgress('失败', 100);
return { success: false, error: String(error) };
}
},
};
// ============================================================================
// Export All Basic Templates
// ============================================================================
export const basicTemplates: TaskTemplate[] = [
navigateScreenshotTemplate,
fillFormTemplate,
clickNavigateTemplate,
getPageInfoTemplate,
executeJsTemplate,
];
|