@pyrokine/mcp-chrome 2.4.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +546 -192
  2. package/README_zh.md +490 -192
  3. package/dist/anti-detection/behavior.js +1 -1
  4. package/dist/anti-detection/behavior.js.map +1 -1
  5. package/dist/anti-detection/injection.d.ts.map +1 -1
  6. package/dist/anti-detection/injection.js +5 -4
  7. package/dist/anti-detection/injection.js.map +1 -1
  8. package/dist/cdp/client.d.ts +2 -2
  9. package/dist/cdp/client.d.ts.map +1 -1
  10. package/dist/cdp/client.js +24 -10
  11. package/dist/cdp/client.js.map +1 -1
  12. package/dist/cdp/launcher.d.ts +2 -3
  13. package/dist/cdp/launcher.d.ts.map +1 -1
  14. package/dist/cdp/launcher.js +84 -24
  15. package/dist/cdp/launcher.js.map +1 -1
  16. package/dist/core/auto-wait.d.ts +3 -3
  17. package/dist/core/auto-wait.d.ts.map +1 -1
  18. package/dist/core/auto-wait.js +45 -20
  19. package/dist/core/auto-wait.js.map +1 -1
  20. package/dist/core/browser-driver.d.ts +104 -14
  21. package/dist/core/browser-driver.d.ts.map +1 -1
  22. package/dist/core/browser-driver.js +1 -0
  23. package/dist/core/browser-driver.js.map +1 -1
  24. package/dist/core/errors.d.ts +25 -0
  25. package/dist/core/errors.d.ts.map +1 -1
  26. package/dist/core/errors.js +93 -1
  27. package/dist/core/errors.js.map +1 -1
  28. package/dist/core/locator.d.ts.map +1 -1
  29. package/dist/core/locator.js +6 -4
  30. package/dist/core/locator.js.map +1 -1
  31. package/dist/core/os-mouse.d.ts +78 -0
  32. package/dist/core/os-mouse.d.ts.map +1 -0
  33. package/dist/core/os-mouse.js +378 -0
  34. package/dist/core/os-mouse.js.map +1 -0
  35. package/dist/core/session.d.ts +46 -21
  36. package/dist/core/session.d.ts.map +1 -1
  37. package/dist/core/session.js +724 -175
  38. package/dist/core/session.js.map +1 -1
  39. package/dist/core/types.d.ts +12 -0
  40. package/dist/core/types.d.ts.map +1 -1
  41. package/dist/core/types.js +2 -0
  42. package/dist/core/types.js.map +1 -1
  43. package/dist/core/unified-session.d.ts +117 -21
  44. package/dist/core/unified-session.d.ts.map +1 -1
  45. package/dist/core/unified-session.js +619 -129
  46. package/dist/core/unified-session.js.map +1 -1
  47. package/dist/core/utils.d.ts +5 -0
  48. package/dist/core/utils.d.ts.map +1 -1
  49. package/dist/core/utils.js +475 -54
  50. package/dist/core/utils.js.map +1 -1
  51. package/dist/extension/bridge.d.ts +61 -35
  52. package/dist/extension/bridge.d.ts.map +1 -1
  53. package/dist/extension/bridge.js +290 -106
  54. package/dist/extension/bridge.js.map +1 -1
  55. package/dist/extension/http-server.d.ts +3 -0
  56. package/dist/extension/http-server.d.ts.map +1 -1
  57. package/dist/extension/http-server.js +25 -3
  58. package/dist/extension/http-server.js.map +1 -1
  59. package/dist/index.js +7 -0
  60. package/dist/index.js.map +1 -1
  61. package/dist/tools/browse.d.ts +1 -1
  62. package/dist/tools/browse.d.ts.map +1 -1
  63. package/dist/tools/browse.js +291 -175
  64. package/dist/tools/browse.js.map +1 -1
  65. package/dist/tools/challenge.d.ts +153 -0
  66. package/dist/tools/challenge.d.ts.map +1 -0
  67. package/dist/tools/challenge.js +611 -0
  68. package/dist/tools/challenge.js.map +1 -0
  69. package/dist/tools/cookies.d.ts.map +1 -1
  70. package/dist/tools/cookies.js +13 -7
  71. package/dist/tools/cookies.js.map +1 -1
  72. package/dist/tools/diagnostics.d.ts +5 -5
  73. package/dist/tools/diagnostics.d.ts.map +1 -1
  74. package/dist/tools/diagnostics.js +39 -20
  75. package/dist/tools/diagnostics.js.map +1 -1
  76. package/dist/tools/evaluate.d.ts.map +1 -1
  77. package/dist/tools/evaluate.js +106 -23
  78. package/dist/tools/evaluate.js.map +1 -1
  79. package/dist/tools/extract.d.ts.map +1 -1
  80. package/dist/tools/extract.js +199 -208
  81. package/dist/tools/extract.js.map +1 -1
  82. package/dist/tools/input.d.ts +1 -1
  83. package/dist/tools/input.d.ts.map +1 -1
  84. package/dist/tools/input.js +523 -175
  85. package/dist/tools/input.js.map +1 -1
  86. package/dist/tools/logs.d.ts.map +1 -1
  87. package/dist/tools/logs.js +7 -7
  88. package/dist/tools/logs.js.map +1 -1
  89. package/dist/tools/manage.d.ts.map +1 -1
  90. package/dist/tools/manage.js +400 -64
  91. package/dist/tools/manage.js.map +1 -1
  92. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  93. package/dist/tools/network-sanitizer.js +1 -0
  94. package/dist/tools/network-sanitizer.js.map +1 -1
  95. package/dist/tools/page-context.d.ts +17 -0
  96. package/dist/tools/page-context.d.ts.map +1 -0
  97. package/dist/tools/page-context.js +103 -0
  98. package/dist/tools/page-context.js.map +1 -0
  99. package/dist/tools/png.d.ts +5 -0
  100. package/dist/tools/png.d.ts.map +1 -1
  101. package/dist/tools/png.js +89 -22
  102. package/dist/tools/png.js.map +1 -1
  103. package/dist/tools/post-condition.d.ts.map +1 -1
  104. package/dist/tools/post-condition.js +17 -5
  105. package/dist/tools/post-condition.js.map +1 -1
  106. package/dist/tools/schema.d.ts +9 -0
  107. package/dist/tools/schema.d.ts.map +1 -1
  108. package/dist/tools/schema.js +15 -0
  109. package/dist/tools/schema.js.map +1 -1
  110. package/dist/tools/target-diagnostics.d.ts +7 -0
  111. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  112. package/dist/tools/target-diagnostics.js +47 -17
  113. package/dist/tools/target-diagnostics.js.map +1 -1
  114. package/dist/tools/wait.d.ts.map +1 -1
  115. package/dist/tools/wait.js +52 -56
  116. package/dist/tools/wait.js.map +1 -1
  117. package/extension/dist/assets/content.ts-C4imZ6A9.js +13 -0
  118. package/extension/dist/assets/content.ts-loader-CnJuCGhl.js +13 -0
  119. package/extension/dist/assets/{index.ts-GG6dPUPX.js → index.ts-GeHNZBml.js} +2156 -1950
  120. package/extension/dist/assets/page-scripts-CMIY1zhd.js +1379 -0
  121. package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-CgtWL6Py.js} +48 -1
  122. package/extension/dist/manifest.json +4 -3
  123. package/extension/dist/service-worker-loader.js +1 -1
  124. package/extension/dist/src/popup/popup.html +54 -44
  125. package/package.json +11 -8
  126. package/scripts/start-chrome.ps1 +58 -0
  127. package/dist/extension/native-host-installer.d.ts +0 -21
  128. package/dist/extension/native-host-installer.d.ts.map +0 -1
  129. package/dist/extension/native-host-installer.js +0 -147
  130. package/dist/extension/native-host-installer.js.map +0 -1
  131. package/dist/extension/socket-server.d.ts +0 -32
  132. package/dist/extension/socket-server.d.ts.map +0 -1
  133. package/dist/extension/socket-server.js +0 -177
  134. package/dist/extension/socket-server.js.map +0 -1
  135. package/dist/extension/ws-server.d.ts +0 -40
  136. package/dist/extension/ws-server.d.ts.map +0 -1
  137. package/dist/extension/ws-server.js +0 -246
  138. package/dist/extension/ws-server.js.map +0 -1
  139. package/dist/native-host/index.js +0 -280
  140. package/dist/native-host/mcp-chrome-host +0 -2
  141. package/extension/dist/assets/content.ts-Cj_iiU2s.js +0 -25
@@ -10,26 +10,29 @@
10
10
  * - state: 页面状态(精简的可交互元素列表)
11
11
  * - metadata: 页面元信息(title/og/jsonLd 等)
12
12
  */
13
- import { readFile } from 'fs/promises';
13
+ import { readFile, stat } from 'fs/promises';
14
14
  import { basename, extname, join } from 'path';
15
15
  import { z } from 'zod';
16
16
  import { CWD_PATH_PREFIX, formatErrorResponse, formatResponse, getSession, getUnifiedSession, resolveScopedOutputPath, TMP_PATH_PREFIX, writePrivateFile, } from '../core/index.js';
17
- import { comparePngImages, MAX_COMPARE_PIXELS, MAX_COMPARE_PNG_BYTES, readPngHeader } from './png.js';
18
- import { targetToFindParams, targetZodSchema } from './schema.js';
19
17
  import { sanitizeUrlRecords } from './network-sanitizer.js';
20
- import { buildTargetDiagnostics, TargetTimeoutError } from './target-diagnostics.js';
18
+ import { withPageContext } from './page-context.js';
19
+ import { assertPngFileBudget, assertScreenshotBase64Budget, assertScreenshotBudget, comparePngImages, MAX_COMPARE_PIXELS, MAX_COMPARE_PNG_BYTES, readPngHeader, } from './png.js';
20
+ import { pageTargetIdSchema, resolvePageTargetId, targetToFindParams, targetZodSchema } from './schema.js';
21
+ import { buildTargetDiagnostics, TargetNotFoundError, TargetTimeoutError } from './target-diagnostics.js';
21
22
  /** 无 output 时附录返回的最大图片数 */
22
23
  const MAX_APPENDIX_IMAGES = 20;
23
24
  /**
24
25
  * extract 参数 schema
25
26
  */
26
- const extractSchema = z.object({
27
+ const extractSchema = z
28
+ .object({
27
29
  type: z
28
30
  .enum(['text', 'html', 'frameHtml', 'attribute', 'screenshot', 'state', 'metadata', 'diagnosticBundle'])
29
31
  .describe('提取类型'),
30
32
  target: targetZodSchema
31
33
  .optional()
32
- .describe('目标元素(attribute 必填;text/html 可选,省略则提取整个页面;screenshot 可选用于元素截图;state 可选(仅 Extension)用于返回目标子树;metadata 不需要)'),
34
+ .describe('目标元素(attribute 必填;text/html 可选,省略则提取整个页面;text 对 HTML 使用 innerText,SVG/XML 使用 textContent;' +
35
+ 'screenshot 可选用于元素截图;state 可选(仅 Extension)用于返回目标子树;metadata 不需要)'),
33
36
  attribute: z.string().optional().describe('属性名(attribute)'),
34
37
  images: z
35
38
  .enum(['info', 'data'])
@@ -65,26 +68,39 @@ const extractSchema = z.object({
65
68
  .string()
66
69
  .optional()
67
70
  .describe(`输出文件路径(可选),相对路径默认写入 ${TMP_PATH_PREFIX},持久化到仓库请显式写 ${CWD_PATH_PREFIX},images=data 时作为输出目录路径`),
68
- tabId: z
69
- .string()
71
+ targetId: pageTargetIdSchema.describe('目标页面 ID(Extension 或 CDP),优先于默认操作目标'),
72
+ tabId: pageTargetIdSchema.describe('旧版目标 Tab ID,与 targetId 相同语义,保留兼容'),
73
+ depth: z
74
+ .number()
75
+ .int()
76
+ .nonnegative()
70
77
  .optional()
71
- .describe('目标 Tab ID(可选,仅 Extension 模式),不指定则使用当前 attach 的 tab,可操作非当前 attach 的 tab,CDP 模式下不支持此参数'),
72
- depth: z.number().optional().describe('DOM 遍历深度限制(state),默认 15,减小可降低返回数据量'),
78
+ .describe('DOM 遍历深度限制(state),默认 15,减小可降低返回数据量'),
73
79
  mode: z
74
80
  .enum(['accessibility', 'domsnapshot'])
75
81
  .optional()
76
- .describe('页面状态提取模式(state 类型有效),accessibility=可访问性树(默认,与原 read_page 一致),domsnapshot=CDP DOMSnapshot 全量快照(仅 CDP 模式)'),
82
+ .describe('页面状态提取模式(state 类型有效),accessibility=可访问性树(默认,与原 read_page 一致),' +
83
+ 'domsnapshot=CDP DOMSnapshot 全量快照(仅 CDP 模式)'),
77
84
  timeout: z.number().optional().describe('等待目标元素超时'),
78
85
  frame: z
79
86
  .union([z.string(), z.number()])
80
87
  .optional()
81
88
  .describe('iframe 定位(可选,仅 Extension 模式),CSS 选择器(如 "iframe#main")或索引(如 0),不指定则在主框架操作'),
89
+ })
90
+ .superRefine((args, context) => {
91
+ if (args.diffOutput && !args.compareWith) {
92
+ context.addIssue({
93
+ code: 'custom',
94
+ path: ['diffOutput'],
95
+ message: 'diffOutput 需要 compareWith 参数',
96
+ });
97
+ }
82
98
  });
83
99
  async function handleExtract(args) {
84
100
  try {
85
101
  const unifiedSession = getUnifiedSession();
86
102
  // 多 tab 并行:临时切换到指定 tab
87
- return await unifiedSession.withTabId(args.tabId, async () => {
103
+ return await withPageContext(unifiedSession, resolvePageTargetId(args), async () => {
88
104
  return await unifiedSession.withFrame(args.frame, async () => {
89
105
  const useExtension = unifiedSession.getMode() === 'extension';
90
106
  const frameHtmlError = validateFrameHtmlArgs(args, useExtension);
@@ -154,7 +170,7 @@ async function handleExtractInFrame(context, args) {
154
170
  }
155
171
  async function handleTextExtract({ unifiedSession, session, useExtension }, args) {
156
172
  const text = useExtension
157
- ? await extractTextExtension(unifiedSession, args.target)
173
+ ? await extractTextExtension(unifiedSession, args.target, args.timeout)
158
174
  : await extractText(session, args.target, args.timeout);
159
175
  if (args.output) {
160
176
  const outputPath = await writeOutputFile(args.output, text, 'utf-8');
@@ -168,7 +184,7 @@ async function handleHtmlExtract(context, args) {
168
184
  return handleHtmlWithImages(unifiedSession, session, useExtension, args);
169
185
  }
170
186
  const html = useExtension
171
- ? await extractHtmlExtension(unifiedSession, args.target)
187
+ ? await extractHtmlExtension(unifiedSession, args.target, true, args.timeout)
172
188
  : await extractHTML(session, args.target, args.timeout);
173
189
  if (args.output) {
174
190
  const outputPath = await writeOutputFile(args.output, html, 'utf-8');
@@ -177,7 +193,7 @@ async function handleHtmlExtract(context, args) {
177
193
  return formatResponse({ success: true, type: 'html', content: html });
178
194
  }
179
195
  async function handleFrameHtmlExtract({ unifiedSession }, args) {
180
- const html = await extractHtmlExtension(unifiedSession, args.target);
196
+ const html = await extractHtmlExtension(unifiedSession, args.target, true, args.timeout);
181
197
  if (args.output) {
182
198
  const outputPath = await writeOutputFile(args.output, html, 'utf-8');
183
199
  return formatResponse({
@@ -198,32 +214,56 @@ async function handleAttributeExtract({ unifiedSession, session, useExtension },
198
214
  return formatErrorResponse(new Error('attribute 提取需要 attribute 参数'));
199
215
  }
200
216
  const value = useExtension
201
- ? await extractAttributeExtension(unifiedSession, args.target, args.attribute)
217
+ ? await extractAttributeExtension(unifiedSession, args.target, args.attribute, args.timeout)
202
218
  : await extractAttribute(session, args.target, args.attribute, args.timeout);
203
219
  return formatResponse({ success: true, type: 'attribute', attribute: args.attribute, value });
204
220
  }
205
221
  async function handleScreenshotExtract({ unifiedSession, useExtension }, args) {
206
222
  let clip;
207
- if (args.target) {
223
+ if (args.target && !args.clip) {
208
224
  const { selector, text, xpath, nth: nthParam } = targetToFindParams(args.target);
209
225
  const nth = nthParam ?? 0;
210
- const found = await unifiedSession.find(selector, text, xpath);
211
- if (found.length > nth) {
212
- const rect = found[nth].rect;
213
- if (rect.width > 0 && rect.height > 0) {
214
- const scrollOffset = args.frame === undefined ? await getPageScrollOffset(unifiedSession, args.timeout) : { x: 0, y: 0 };
215
- clip = {
216
- x: rect.x + scrollOffset.x,
217
- y: rect.y + scrollOffset.y,
218
- width: rect.width,
219
- height: rect.height,
220
- };
221
- }
226
+ const pointTarget = 'x' in args.target && 'y' in args.target ? args.target : null;
227
+ const found = pointTarget
228
+ ? useExtension
229
+ ? await unifiedSession.findAtPoint(pointTarget.x, pointTarget.y, nth, args.timeout)
230
+ : await unifiedSession
231
+ .evaluate(`(() => {
232
+ const element = document.elementFromPoint(${pointTarget.x}, ${pointTarget.y});
233
+ if (!element) return null;
234
+ const rect = element.getBoundingClientRect();
235
+ return {
236
+ refId: '', tag: element.tagName.toLowerCase(), text: '',
237
+ rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }
238
+ };
239
+ })()`, undefined, args.timeout)
240
+ .then((element) => (element && nth === 0 ? [element] : []))
241
+ : await unifiedSession.find(selector, text, xpath, args.timeout);
242
+ const target = found[pointTarget ? 0 : nth];
243
+ if (!target || target.rect.width <= 0 || target.rect.height <= 0) {
244
+ throw new TargetNotFoundError(await buildTargetDiagnostics(unifiedSession, args.target, {
245
+ nth,
246
+ timeout: args.timeout,
247
+ frame: args.frame,
248
+ matchCount: found.length,
249
+ lastState: target ? 'zero-size' : 'not-found',
250
+ candidates: found,
251
+ }));
222
252
  }
253
+ const scrollOffset = args.frame === undefined ? await getPageScrollOffset(unifiedSession, args.timeout) : { x: 0, y: 0 };
254
+ clip = {
255
+ x: target.rect.x + scrollOffset.x,
256
+ y: target.rect.y + scrollOffset.y,
257
+ width: target.rect.width,
258
+ height: target.rect.height,
259
+ };
223
260
  }
224
261
  clip = args.clip ?? clip;
225
262
  const fullPage = clip ? false : (args.fullPage ?? false);
226
263
  const scale = args.scale ?? 1;
264
+ if (clip) {
265
+ assertScreenshotBudget(clip.width, clip.height, scale);
266
+ }
227
267
  const screenshot = await unifiedSession.screenshot({
228
268
  fullPage,
229
269
  scale: args.scale,
@@ -231,6 +271,7 @@ async function handleScreenshotExtract({ unifiedSession, useExtension }, args) {
231
271
  quality: args.quality,
232
272
  clip,
233
273
  });
274
+ assertScreenshotBase64Budget(screenshot.data);
234
275
  const screenshotBuffer = Buffer.from(screenshot.data, 'base64');
235
276
  const encodedDimensions = readImageDimensions(screenshotBuffer, screenshot.format);
236
277
  const fallbackDimensions = encodedDimensions
@@ -247,14 +288,16 @@ async function handleScreenshotExtract({ unifiedSession, useExtension }, args) {
247
288
  clip,
248
289
  size: screenshotBuffer.length,
249
290
  byteSize: screenshotBuffer.length,
250
- capabilities: screenshotCapabilities(useExtension),
291
+ capabilities: screenshotCapabilities(),
251
292
  };
252
293
  if (args.compareWith) {
253
294
  if (screenshot.format !== 'png') {
254
295
  throw new Error('screenshot compare 仅支持 png 格式');
255
296
  }
256
297
  const baselinePath = await resolveScopedOutputPath(args.compareWith, 'mcp-chrome');
298
+ assertPngFileBudget((await stat(baselinePath.absolutePath)).size);
257
299
  const baseline = await readFile(baselinePath.absolutePath);
300
+ assertPngFileBudget(baseline.length);
258
301
  const comparison = comparePngImages(baseline, screenshotBuffer);
259
302
  metadata.comparison = {
260
303
  pixelDiffRatio: comparison.pixelDiffRatio,
@@ -289,11 +332,20 @@ async function handleStateExtract({ unifiedSession, useExtension }, args) {
289
332
  }
290
333
  let refId;
291
334
  if (args.target && useExtension) {
292
- const { selector, text, xpath, nth: nthParam } = targetToFindParams(args.target);
293
- const nth = nthParam ?? 0;
294
- const elements = await unifiedSession.find(selector, text, xpath);
295
- if (elements.length > 0 && nth < elements.length) {
296
- refId = elements[nth].refId;
335
+ refId = await findTargetRefExtension(unifiedSession, args.target, args.timeout);
336
+ if (!refId) {
337
+ const { selector, text, xpath, nth: nthParam, } = targetToFindParams(args.target);
338
+ const candidates = 'x' in args.target && 'y' in args.target
339
+ ? await unifiedSession.findAtPoint(args.target.x, args.target.y)
340
+ : await unifiedSession.find(selector, text, xpath, args.timeout);
341
+ throw new TargetNotFoundError(await buildTargetDiagnostics(unifiedSession, args.target, {
342
+ nth: nthParam ?? 0,
343
+ timeout: args.timeout,
344
+ frame: args.frame,
345
+ matchCount: candidates.length,
346
+ lastState: 'not-found',
347
+ candidates,
348
+ }));
297
349
  }
298
350
  }
299
351
  const readPageOptions = {};
@@ -338,10 +390,10 @@ async function handleDomSnapshotState(unifiedSession, useExtension, args) {
338
390
  }
339
391
  return formatResponse({ success: true, type: 'state', mode: 'domsnapshot', snapshot });
340
392
  }
341
- async function handleDiagnosticBundleExtract({ unifiedSession, useExtension }, args) {
393
+ async function handleDiagnosticBundleExtract({ unifiedSession }, args) {
342
394
  const state = await unifiedSession.getLiveState().catch(() => null);
343
395
  const metadata = await unifiedSession.getMetadata();
344
- const frames = useExtension ? await unifiedSession.getFrames() : { frames: [] };
396
+ const frames = await unifiedSession.getFrames();
345
397
  await unifiedSession.enableConsole();
346
398
  await unifiedSession.enableNetwork();
347
399
  const consoleLogs = sanitizeUrlRecords(await unifiedSession.getConsoleLogs());
@@ -366,8 +418,8 @@ async function handleDiagnosticBundleExtract({ unifiedSession, useExtension }, a
366
418
  },
367
419
  capabilities: {
368
420
  screenshot: true,
369
- hiddenTabScreenshot: useExtension,
370
- frames: useExtension,
421
+ hiddenTabScreenshot: false,
422
+ frames: true,
371
423
  },
372
424
  };
373
425
  const summary = {
@@ -392,9 +444,9 @@ async function handleDiagnosticBundleExtract({ unifiedSession, useExtension }, a
392
444
  failedRequests: bundle.networkSummary.recentFailures,
393
445
  });
394
446
  }
395
- async function handleMetadataExtract({ unifiedSession, useExtension }, args) {
447
+ async function handleMetadataExtract({ unifiedSession }, args) {
396
448
  const metadata = await unifiedSession.getMetadata();
397
- const frames = useExtension ? await unifiedSession.getFrames() : { frames: [] };
449
+ const frames = await unifiedSession.getFrames();
398
450
  if (args.output) {
399
451
  const outputPath = await writeOutputFile(args.output, JSON.stringify({ ...metadata, ...frames }, null, 2), 'utf-8');
400
452
  return formatResponse({ success: true, type: 'metadata', output: outputPath });
@@ -434,7 +486,10 @@ async function getScreenshotFallbackDimensions(unifiedSession, clip, fullPage, s
434
486
  }
435
487
  try {
436
488
  const size = await unifiedSession.evaluate(fullPage
437
- ? '(() => ({ width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight }))()'
489
+ ? `(() => ({
490
+ width: document.documentElement.scrollWidth,
491
+ height: document.documentElement.scrollHeight,
492
+ }))()`
438
493
  : '(() => ({ width: window.innerWidth, height: window.innerHeight }))()', undefined, timeout);
439
494
  return {
440
495
  width: Math.round(size.width * scale),
@@ -446,13 +501,13 @@ async function getScreenshotFallbackDimensions(unifiedSession, clip, fullPage, s
446
501
  return undefined;
447
502
  }
448
503
  }
449
- function screenshotCapabilities(useExtension) {
504
+ function screenshotCapabilities() {
450
505
  return {
451
506
  formats: ['png', 'jpeg', 'webp'],
452
507
  clip: true,
453
508
  fullPage: true,
454
509
  scale: true,
455
- hiddenTabScreenshot: useExtension,
510
+ hiddenTabScreenshot: false,
456
511
  compare: {
457
512
  formats: ['png'],
458
513
  maxBytes: MAX_COMPARE_PNG_BYTES,
@@ -556,37 +611,44 @@ function readWebpDimensions(buffer) {
556
611
  * 处理 html + images 提取
557
612
  */
558
613
  async function handleHtmlWithImages(unifiedSession, session, useExtension, args) {
559
- const { selector, nth: nthParam } = args.target
560
- ? targetToFindParams(args.target)
561
- : { selector: undefined, nth: undefined };
562
- const nth = nthParam ?? 0;
563
614
  let result;
564
- if (selector && nth > 0) {
565
- // nth > 0:用 evaluate 取第 N 个匹配元素
566
- result = await unifiedSession.evaluate(`(function(s, n) {
567
- var els = document.querySelectorAll(s);
568
- if (n >= els.length) return {html: '', images: []};
569
- var root = els[n];
570
- var html = root.outerHTML;
571
- var imgList = [];
572
- if (root.tagName === 'IMG') imgList.push(root);
573
- root.querySelectorAll('img').forEach(function(img) { imgList.push(img); });
574
- var images = [];
575
- for (var i = 0; i < imgList.length; i++) {
576
- var img = imgList[i];
577
- images.push({index: i, src: img.src, dataSrc: (function() {
578
- var raw = img.dataset.src || img.dataset.lazySrc || img.dataset.original || '';
579
- if (!raw) return ''; try { return new URL(raw, location.href).href } catch(e) { return raw }
580
- })(), alt: img.alt, width: img.width, height: img.height,
581
- naturalWidth: img.naturalWidth, naturalHeight: img.naturalHeight});
582
- }
583
- return {html: html, images: images};
584
- })`, undefined, undefined, [selector, nth]);
615
+ if (args.target) {
616
+ const { selector, text, xpath, nth: nthParam } = targetToFindParams(args.target);
617
+ const nth = nthParam ?? 0;
618
+ if (useExtension) {
619
+ const refId = await findTargetRefExtension(unifiedSession, args.target, args.timeout);
620
+ if (!refId) {
621
+ const matches = 'x' in args.target && 'y' in args.target
622
+ ? await unifiedSession.findAtPoint(args.target.x, args.target.y)
623
+ : await unifiedSession.find(selector, text, xpath, args.timeout);
624
+ throw new TargetNotFoundError(await buildTargetDiagnostics(unifiedSession, args.target, {
625
+ nth,
626
+ timeout: args.timeout,
627
+ matchCount: matches.length,
628
+ lastState: 'not-found',
629
+ candidates: matches,
630
+ }));
631
+ }
632
+ result = await unifiedSession.getHtmlWithImagesByRef(refId);
633
+ }
634
+ else {
635
+ const matches = await unifiedSession.find(selector, text, xpath, args.timeout);
636
+ if (matches.length <= nth) {
637
+ throw new TargetNotFoundError(await buildTargetDiagnostics(unifiedSession, args.target, {
638
+ nth,
639
+ timeout: args.timeout,
640
+ matchCount: matches.length,
641
+ lastState: 'not-found',
642
+ candidates: matches,
643
+ }));
644
+ }
645
+ result = await extractHtmlWithImagesByTarget(unifiedSession, selector, text, xpath, nth, args.timeout);
646
+ }
585
647
  }
586
648
  else {
587
649
  result = useExtension
588
- ? await unifiedSession.getHtmlWithImages(selector)
589
- : await extractHtmlWithImagesCdp(session, selector, args.timeout);
650
+ ? await unifiedSession.getHtmlWithImages()
651
+ : await extractHtmlWithImagesCdp(session, undefined, args.timeout);
590
652
  }
591
653
  if (args.images === 'info') {
592
654
  // info 模式:HTML + 图片元信息
@@ -623,6 +685,49 @@ async function handleHtmlWithImages(unifiedSession, session, useExtension, args)
623
685
  // 无 output:MCP 附录方式返回
624
686
  return buildImageAppendixResponse(result.html, result.images, imageDataList);
625
687
  }
688
+ async function extractHtmlWithImagesByTarget(unifiedSession, selector, text, xpath, nth, timeout) {
689
+ return unifiedSession.evaluate(`(function(selector, text, xpath, nth) {
690
+ var candidates = [];
691
+ if (xpath) {
692
+ var snapshot = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
693
+ for (var i = 0; i < snapshot.snapshotLength; i++) candidates.push(snapshot.snapshotItem(i));
694
+ } else if (selector) {
695
+ candidates = Array.from(document.querySelectorAll(selector));
696
+ } else if (text) {
697
+ candidates = Array.from(document.querySelectorAll('*')).filter(function(element) {
698
+ return (element.textContent || '').includes(text);
699
+ });
700
+ }
701
+ if (text && (selector || xpath)) {
702
+ candidates = candidates.filter(function(element) {
703
+ return (element.textContent || '').includes(text);
704
+ });
705
+ }
706
+ var root = candidates[nth];
707
+ if (!root || !root.outerHTML) return { html: '', images: [] };
708
+ var imageNodes = [];
709
+ if (root.tagName === 'IMG') imageNodes.push(root);
710
+ root.querySelectorAll('img').forEach(function(img) { imageNodes.push(img); });
711
+ var images = imageNodes.map(function(img, index) {
712
+ var raw = img.dataset.src || img.dataset.lazySrc || img.dataset.original || '';
713
+ var dataSrc = '';
714
+ if (raw) {
715
+ try { dataSrc = new URL(raw, location.href).href } catch (error) { dataSrc = raw }
716
+ }
717
+ return {
718
+ index: index,
719
+ src: img.src,
720
+ dataSrc: dataSrc,
721
+ alt: img.alt,
722
+ width: img.width,
723
+ height: img.height,
724
+ naturalWidth: img.naturalWidth,
725
+ naturalHeight: img.naturalHeight
726
+ };
727
+ });
728
+ return { html: root.outerHTML, images: images };
729
+ })`, undefined, timeout, [selector ?? null, text ?? null, xpath ?? null, nth]);
730
+ }
626
731
  /**
627
732
  * CDP 模式:提取 HTML + 图片元信息
628
733
  */
@@ -889,7 +994,7 @@ async function extractText(session, target, timeout) {
889
994
  if (target) {
890
995
  const locator = session.createLocator(target, timeout !== undefined ? { timeout } : undefined);
891
996
  const text = await locator.evaluateOn(`function() {
892
- return this.textContent ?? '';
997
+ return this instanceof HTMLElement ? this.innerText : (this.textContent ?? '');
893
998
  }`);
894
999
  return text ?? '';
895
1000
  }
@@ -932,162 +1037,47 @@ async function extractAttribute(session, target, attribute, timeout) {
932
1037
  return this.getAttribute(${JSON.stringify(attribute)});
933
1038
  }`);
934
1039
  }
1040
+ async function findTargetRefExtension(unifiedSession, target, timeout) {
1041
+ const { selector, text, xpath, nth } = targetToFindParams(target);
1042
+ const matches = 'x' in target && 'y' in target
1043
+ ? await unifiedSession.findAtPoint(target.x, target.y, nth ?? 0, timeout)
1044
+ : await unifiedSession.find(selector, text, xpath, timeout, nth ?? 0);
1045
+ return matches[0]?.refId;
1046
+ }
935
1047
  /**
936
1048
  * Extension 模式:提取文本
937
1049
  * 支持所有 Target 形式(css/xpath/text/role/label 等)
938
1050
  */
939
- async function extractTextExtension(unifiedSession, target) {
1051
+ async function extractTextExtension(unifiedSession, target, timeout) {
940
1052
  if (!target) {
941
1053
  return unifiedSession.getText();
942
1054
  }
943
- if ('x' in target && 'y' in target && typeof target.x === 'number' && typeof target.y === 'number') {
944
- const expr = '(function(x, y) { var el = document.elementFromPoint(x, y); ' +
945
- "return el ? (el.textContent || '') : '' })";
946
- return unifiedSession.evaluate(expr, undefined, undefined, [target.x, target.y]);
947
- }
948
- const { selector, text, xpath, nth: nthParam } = targetToFindParams(target);
949
- const nth = nthParam ?? 0;
950
- if (selector) {
951
- if (text) {
952
- const expr = '(function(s, t, n) { var els = Array.from(document.querySelectorAll(s))' +
953
- '.filter(function(e) { return (e.textContent || "").includes(t); }); ' +
954
- "return n < els.length ? (els[n].textContent || '') : '' })";
955
- return unifiedSession.evaluate(expr, undefined, undefined, [selector, text, nth]);
956
- }
957
- if (nth > 0) {
958
- const expr = '(function(s, n) { var els = document.querySelectorAll(s); ' +
959
- "return n < els.length ? (els[n].textContent || '') : '' })";
960
- return unifiedSession.evaluate(expr, undefined, undefined, [selector, nth]);
961
- }
962
- return unifiedSession.getText(selector);
963
- }
964
- // xpath/text 定位:通过 evaluate 在页面上下文中查找
965
- if (xpath) {
966
- const expr = '(function(xp, n) { var r = document.evaluate(xp, document, null, ' +
967
- 'XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); ' +
968
- "return n < r.snapshotLength ? (r.snapshotItem(n).textContent || '') : '' })";
969
- return unifiedSession.evaluate(expr, undefined, undefined, [xpath, nth]);
970
- }
971
- if (text) {
972
- const expr = '(function(t, n) { var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); ' +
973
- 'var found = []; var seen = new WeakSet(); var node; ' +
974
- 'while ((node = walker.nextNode())) { if (node.textContent && node.textContent.includes(t) ' +
975
- '&& node.parentElement && !seen.has(node.parentElement)) { ' +
976
- 'seen.add(node.parentElement); found.push(node.parentElement); } } ' +
977
- "return n < found.length ? (found[n].textContent || '') : '' })";
978
- return unifiedSession.evaluate(expr, undefined, undefined, [text, nth]);
979
- }
980
- return unifiedSession.getText();
1055
+ const refId = await findTargetRefExtension(unifiedSession, target, timeout);
1056
+ return refId ? unifiedSession.getTextByRef(refId) : '';
981
1057
  }
982
1058
  /**
983
1059
  * Extension 模式:提取 HTML
984
1060
  * 支持所有 Target 形式(css/xpath/text/role/label 等)
985
1061
  */
986
- async function extractHtmlExtension(unifiedSession, target, outer = true) {
1062
+ async function extractHtmlExtension(unifiedSession, target, outer = true, timeout) {
987
1063
  if (!target) {
988
1064
  return unifiedSession.getHtml(undefined, outer);
989
1065
  }
990
- const prop = outer ? 'outerHTML' : 'innerHTML';
991
- if ('x' in target && 'y' in target && typeof target.x === 'number' && typeof target.y === 'number') {
992
- const expr = '(function(x, y, p) { var el = document.elementFromPoint(x, y); ' + "return el ? (el[p] || '') : '' })";
993
- return unifiedSession.evaluate(expr, undefined, undefined, [target.x, target.y, prop]);
994
- }
995
- const { selector, text, xpath, nth: nthParam } = targetToFindParams(target);
996
- const nth = nthParam ?? 0;
997
- if (selector) {
998
- if (text) {
999
- const expr = '(function(s, t, n, p) { var els = Array.from(document.querySelectorAll(s))' +
1000
- '.filter(function(e) { return (e.textContent || "").includes(t); }); ' +
1001
- "return n < els.length ? (els[n][p] || '') : '' })";
1002
- return unifiedSession.evaluate(expr, undefined, undefined, [selector, text, nth, prop]);
1003
- }
1004
- if (nth > 0) {
1005
- const expr = '(function(s, n, p) { var els = document.querySelectorAll(s); ' +
1006
- "return n < els.length ? (els[n][p] || '') : '' })";
1007
- return unifiedSession.evaluate(expr, undefined, undefined, [selector, nth, prop]);
1008
- }
1009
- return unifiedSession.getHtml(selector, outer);
1010
- }
1011
- if (xpath) {
1012
- const expr = '(function(xp, n, p) { var r = document.evaluate(xp, document, null, ' +
1013
- 'XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); ' +
1014
- "return n < r.snapshotLength ? (r.snapshotItem(n)[p] || '') : '' })";
1015
- return unifiedSession.evaluate(expr, undefined, undefined, [xpath, nth, prop]);
1016
- }
1017
- if (text) {
1018
- const expr = '(function(t, n, p) { var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); ' +
1019
- 'var found = []; var seen = new WeakSet(); var node; ' +
1020
- 'while ((node = walker.nextNode())) { if (node.textContent && node.textContent.includes(t) ' +
1021
- '&& node.parentElement && !seen.has(node.parentElement)) { ' +
1022
- 'seen.add(node.parentElement); found.push(node.parentElement); } } ' +
1023
- "return n < found.length ? (found[n][p] || '') : '' })";
1024
- return unifiedSession.evaluate(expr, undefined, undefined, [text, nth, prop]);
1025
- }
1026
- return unifiedSession.getHtml(undefined, outer);
1066
+ const refId = await findTargetRefExtension(unifiedSession, target, timeout);
1067
+ return refId ? unifiedSession.getHtmlByRef(refId, outer) : '';
1027
1068
  }
1028
1069
  /**
1029
1070
  * Extension 模式:提取属性
1030
1071
  */
1031
- async function extractAttributeExtension(unifiedSession, target, attribute) {
1032
- if ('x' in target && 'y' in target && typeof target.x === 'number' && typeof target.y === 'number') {
1033
- if (attribute.startsWith('computed:')) {
1034
- const prop = attribute.slice('computed:'.length);
1035
- const expr = '(function(x, y, p) { var el = document.elementFromPoint(x, y); ' +
1036
- 'return el ? window.getComputedStyle(el).getPropertyValue(p) : null })';
1037
- return unifiedSession.evaluate(expr, undefined, undefined, [target.x, target.y, prop]);
1038
- }
1039
- const expr = '(function(x, y, a) { var el = document.elementFromPoint(x, y); ' +
1040
- 'return el ? el.getAttribute(a) : null })';
1041
- return unifiedSession.evaluate(expr, undefined, undefined, [target.x, target.y, attribute]);
1042
- }
1043
- const { selector, text, xpath, nth: nthParam } = targetToFindParams(target);
1044
- // computed style: computed:color → getComputedStyle(el)
1045
- if (attribute.startsWith('computed:')) {
1046
- const prop = attribute.slice('computed:'.length);
1047
- return extractComputedStyleExtension(unifiedSession, selector, text, xpath, nthParam ?? 0, prop);
1048
- }
1049
- // xpath 定位(含 text+xpath)或 text 且无 selector 时:先 find 得到 refId,再获取属性
1050
- if (xpath || (text && !selector)) {
1051
- const elements = await unifiedSession.find(selector, text, xpath);
1052
- if (elements.length > 0) {
1053
- const nth = nthParam ?? 0;
1054
- if (nth >= elements.length) {
1055
- throw new Error(`第 ${nth} 个匹配元素不存在(共 ${elements.length} 个)`);
1056
- }
1057
- return unifiedSession.getAttribute(undefined, elements[nth].refId, attribute);
1058
- }
1072
+ async function extractAttributeExtension(unifiedSession, target, attribute, timeout) {
1073
+ const refId = await findTargetRefExtension(unifiedSession, target, timeout);
1074
+ if (!refId) {
1059
1075
  return null;
1060
1076
  }
1061
- if (selector) {
1062
- const nth = nthParam ?? 0;
1063
- if (text) {
1064
- // selector + text 组合:find 已实现 AND 过滤
1065
- const elements = await unifiedSession.find(selector, text, undefined);
1066
- if (nth >= elements.length) {
1067
- return null;
1068
- }
1069
- return unifiedSession.getAttribute(undefined, elements[nth].refId, attribute);
1070
- }
1071
- if (nth > 0) {
1072
- const expr = '(function(s, n, a) { var els = document.querySelectorAll(s); ' +
1073
- 'return n < els.length ? els[n].getAttribute(a) : null })';
1074
- return unifiedSession.evaluate(expr, undefined, undefined, [selector, nth, attribute]);
1075
- }
1076
- return unifiedSession.getAttribute(selector, undefined, attribute);
1077
- }
1078
- return null;
1079
- }
1080
- /**
1081
- * Extension 模式:提取 computed style
1082
- */
1083
- async function extractComputedStyleExtension(unifiedSession, selector, text, xpath, nth, prop) {
1084
- const elements = await unifiedSession.find(selector, text, xpath);
1085
- if (elements.length === 0 || nth >= elements.length) {
1086
- return null;
1077
+ if (attribute.startsWith('computed:')) {
1078
+ return unifiedSession.getComputedStyleByRef(refId, attribute.slice('computed:'.length));
1087
1079
  }
1088
- const refId = elements[nth].refId;
1089
- // 通过 Extension ISOLATED 世界执行(访问 __mcpElementMap),避免 MAIN 世界找不到 refId
1090
- return unifiedSession.getComputedStyle(refId, prop);
1080
+ return unifiedSession.getAttributeByRef(refId, attribute);
1091
1081
  }
1092
1082
  /**
1093
1083
  * Extension 模式:等待目标元素出现
@@ -1126,10 +1116,11 @@ async function waitForTargetExtension(unifiedSession, target, timeout, frame) {
1126
1116
  continue;
1127
1117
  }
1128
1118
  try {
1129
- const elements = await unifiedSession.find(selector, text, xpath, remaining);
1119
+ const indexed = nth >= 50;
1120
+ const elements = await unifiedSession.find(selector, text, xpath, remaining, indexed ? nth : undefined);
1130
1121
  matchCount = elements.length;
1131
1122
  candidates = elements;
1132
- if (elements.length > nth) {
1123
+ if (indexed ? elements.length > 0 : elements.length > nth) {
1133
1124
  return;
1134
1125
  }
1135
1126
  }