Skip to content

Chrome DevTools for coding agents

feat: support evaluating scripts from local files (#2606)

achideal9cf47a44558d
diff --git a/docs/tool-reference.md b/docs/tool-reference.md
index 08c9a3ac..2524cdbc 100644
--- a/docs/tool-reference.md
+++ b/docs/tool-reference.md
@@ -375,18 +375,20 @@
### `evaluate_script`
-**Description:** Evaluate a JavaScript function inside the target page. Returns the response as JSON, so returned values have to be JSON-serializable.
+**Description:** Evaluate JavaScript inside the target page. The source can be provided inline or loaded from a local file. Returns the response as JSON, so returned values have to be JSON-serializable.
**Parameters:**
-- **function** (string) **(required)**: A JavaScript function declaration to be executed by the tool in the target page.
- Example without arguments: `() => document.title` or `async () => await fetch("example.com")`.
- Example with arguments: `(el) => el.innerText`
-
- **pageId** (number) **(required)**: Targets a specific page by ID.
- **args** (array) _(optional)_: An optional list of arguments to pass to the function.
- **dialogAction** (string) _(optional)_: Handle dialogs while execution. "accept", "dismiss", or string for response of window.prompt. Defaults to accept.
- **filePath** (string) _(optional)_: The absolute or relative path to a file to save the script output to. If omitted, the output is returned inline.
+- **format** (enum: "function", "script") _(optional)_: How to interpret the source. "function" treats it as a function declaration and supports args. "script" evaluates it as classic JavaScript and does not support args. Defaults to "function". ECMAScript modules are not supported.
+- **function** (string) _(optional)_: JavaScript source to execute in the target page. Provide either this or sourcePath, but not both. The source is interpreted according to format.
+ Example without arguments: `() => document.title` or `async () => await fetch("example.com")`.
+ Example with arguments: `(el) => el.innerText`
+
+- **sourcePath** (string) _(optional)_: The absolute or relative path to a JavaScript file on the MCP server's local filesystem. Provide either this or function, but not both.
- **waitForStableDom** (boolean) _(optional)_: Whether to wait for the DOM to settle. Pass false if the script only reads data. Defaults to true.
---
diff --git a/skills/chrome-devtools-cli/SKILL.md b/skills/chrome-devtools-cli/SKILL.md
index 8292c8f2..f348b186 100644
--- a/skills/chrome-devtools-cli/SKILL.md
+++ b/skills/chrome-devtools-cli/SKILL.md
@@ -134,6 +134,7 @@ chrome-devtools list_network_requests 1 --includePreservedRequests true # Includ
```bash
chrome-devtools evaluate_script "() => document.title" --pageId 1 # Evaluate a JavaScript function on page 1
chrome-devtools evaluate_script "(a) => a.innerText" --pageId 1 --args 1_4 # Evaluate JS with UID arguments on page 1
+chrome-devtools evaluate_script --pageId 1 --sourcePath /path/to/script.js --format script # Evaluate a local classic JavaScript file on page 1
chrome-devtools get_console_message 1 1 # Gets a console message by its ID
chrome-devtools get_css_styles 1 "1_4" # Get CSS styles with pagination on page 1 (default: 10 rules, pageIdx 0)
chrome-devtools get_css_styles 1 "1_4" --pageSize 20 --pageIdx 1 # Paginate CSS rules with custom page size and custom 0-based page index
diff --git a/src/bin/chrome-devtools.ts b/src/bin/chrome-devtools.ts
index 812ba369..cdcf728a 100644
--- a/src/bin/chrome-devtools.ts
+++ b/src/bin/chrome-devtools.ts
@@ -30,7 +30,7 @@ import {hideBin, yargs, type CallToolResult} from '../third_party/index.js';
import {checkForUpdates} from '../utils/check-for-updates.js';
import {VERSION} from '../version.js';
-import {buildCommand} from '../config/cli-commands.js';
+import {buildCommand, isOptionalPositionalArg} from '../config/cli-commands.js';
import {commands} from '../config/cli-options.js';
import {mcpOptions, getCliOptions} from '../config/mcp-options.js';
@@ -99,7 +99,10 @@ const y = yargs(hideBin(process.argv))
);
console.error(' - CORRECT: chrome-devtools click 1 "1_2"');
console.error(
- '2. Optional parameters are passed as double-dash options/flags (e.g. --dblClick true).',
+ ' - CORRECT: chrome-devtools evaluate_script "() => document.title" --pageId 1',
+ );
+ console.error(
+ '2. Optional parameters are passed as double-dash options/flags (e.g. --dblClick true), except optional positional parameters shown in command help.',
);
console.error(
'3. Make sure to escape quotes properly for your shell environment.',
@@ -205,7 +208,7 @@ for (const [commandName, commandDef] of Object.entries(commands)) {
? 'array'
: 'string';
- if (opt.required) {
+ if (opt.required || isOptionalPositionalArg(commandName, argName)) {
const options: PositionalOptions = {
describe: opt.description,
type: type as PositionalOptions['type'],
diff --git a/src/config/cli-commands.ts b/src/config/cli-commands.ts
index 36805b98..03163e1e 100644
--- a/src/config/cli-commands.ts
+++ b/src/config/cli-commands.ts
@@ -6,12 +6,22 @@
import type {ArgDef} from './cli-options.js';
+const OPTIONAL_POSITIONAL_ARGS = new Set(['evaluate_script:function']);
+
+export function isOptionalPositionalArg(
+ commandName: string,
+ argName: string,
+): boolean {
+ return OPTIONAL_POSITIONAL_ARGS.has(`${commandName}:${argName}`);
+}
+
/**
* Builds the yargs command string and usage line for a CLI command.
*
- * Optional args are rendered as `[--flag]` in the usage line only: as part of
- * the command string yargs parses each one as a trailing positional, and a
- * variadic positional has to be the last one.
+ * Optional flag args are rendered as `[--flag]` in the usage line only: as
+ * part of the command string yargs parses each one as a trailing positional,
+ * and a variadic positional has to be the last one. A small set of optional
+ * args intentionally remain positional for backwards-compatible CLI syntax.
*/
export function buildCommand(
commandName: string,
@@ -22,6 +32,8 @@ export function buildCommand(
for (const [name, arg] of Object.entries(args)) {
if (arg.required) {
command += arg.type === 'array' ? ` <${name}..>` : ` <${name}>`;
+ } else if (isOptionalPositionalArg(commandName, name)) {
+ command += arg.type === 'array' ? ` [${name}..]` : ` [${name}]`;
} else {
flags += ` [--${name}]`;
}
diff --git a/src/config/cli-options.ts b/src/config/cli-options.ts
index 69dbfa37..c3834395 100644
--- a/src/config/cli-options.ts
+++ b/src/config/cli-options.ts
@@ -287,7 +287,7 @@ export const commands: Commands = {
},
evaluate_script: {
description:
- 'Evaluate a JavaScript function inside the target page or service worker. Returns the response as JSON, so returned values have to be JSON-serializable.',
+ 'Evaluate JavaScript inside the target page or service worker. The source can be provided inline or loaded from a local file. Returns the response as JSON, so returned values have to be JSON-serializable.',
category: 'Debugging',
args: {
pageId: {
@@ -301,8 +301,23 @@ export const commands: Commands = {
name: 'function',
type: 'string',
description:
- 'A JavaScript function declaration to be executed by the tool in the target page.\nExample without arguments: `() => document.title` or `async () => await fetch("example.com")`.\nExample with arguments: `(el) => el.innerText`\n',
- required: true,
+ 'JavaScript source to execute in the target page. Provide either this or sourcePath, but not both. The source is interpreted according to format.\nExample without arguments: `() => document.title` or `async () => await fetch("example.com")`.\nExample with arguments: `(el) => el.innerText`\n',
+ required: false,
+ },
+ sourcePath: {
+ name: 'sourcePath',
+ type: 'string',
+ description:
+ "The absolute or relative path to a JavaScript file on the MCP server's local filesystem. Provide either this or function, but not both.",
+ required: false,
+ },
+ format: {
+ name: 'format',
+ type: 'string',
+ description:
+ 'How to interpret the source. "function" treats it as a function declaration and supports args. "script" evaluates it as classic JavaScript and does not support args. Defaults to "function". ECMAScript modules are not supported.',
+ required: false,
+ enum: ['function', 'script'],
},
args: {
name: 'args',
diff --git a/src/telemetry/tool_call_metrics.json b/src/telemetry/tool_call_metrics.json
index 2126df0c..8bb87210 100644
--- a/src/telemetry/tool_call_metrics.json
+++ b/src/telemetry/tool_call_metrics.json
@@ -143,6 +143,14 @@
{
"name": "page_id",
"argType": "number"
+ },
+ {
+ "name": "source_path_length",
+ "argType": "number"
+ },
+ {
+ "name": "format",
+ "argType": "string"
}
]
},
diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.ts
index bbd3425b..ec978cdc 100644
--- a/src/tools/ToolDefinition.ts
+++ b/src/tools/ToolDefinition.ts
@@ -281,6 +281,7 @@ export type Context = Readonly<{
clientProvidedFilePath: string,
extension: SupportedExtensions,
): Promise<{filename: string}>;
+ loadResource(path: string): Promise<string>;
getScreenRecorder(): {recorder: ScreenRecorder; filePath: string} | null;
setScreenRecorder(
diff --git a/src/tools/script.ts b/src/tools/script.ts
index 7d3eed7d..5f3584c4 100644
--- a/src/tools/script.ts
+++ b/src/tools/script.ts
@@ -4,6 +4,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
+import {pathToFileURL} from 'node:url';
+
import type {ParsedArguments} from '../config/ConfigParser.js';
import {zod} from '../third_party/index.js';
import type {Frame, JSHandle, Page, WebWorker} from '../third_party/index.js';
@@ -18,7 +20,7 @@ export type Evaluatable = Page | Frame | WebWorker;
export const evaluateScript = defineTool((cliArgs: ParsedArguments) => {
return {
name: 'evaluate_script',
- description: `Evaluate a JavaScript function inside the target page${cliArgs.categoryExtensions ? ' or service worker' : ''}. Returns the response as JSON, so returned values have to be JSON-serializable.`,
+ description: `Evaluate JavaScript inside the target page${cliArgs.categoryExtensions ? ' or service worker' : ''}. The source can be provided inline or loaded from a local file. Returns the response as JSON, so returned values have to be JSON-serializable.`,
annotations: {
category: ToolCategory.DEBUGGING,
readOnlyHint: false,
@@ -37,12 +39,27 @@ export const evaluateScript = defineTool((cliArgs: ParsedArguments) => {
}
: pageIdSchema
: {}),
- function: zod.string().describe(
- `A JavaScript function declaration to be executed by the tool in the target page.
+ function: zod
+ .string()
+ .optional()
+ .describe(
+ `JavaScript source to execute in the target page. Provide either this or sourcePath, but not both. The source is interpreted according to format.
Example without arguments: \`() => document.title\` or \`async () => await fetch("example.com")\`.
Example with arguments: \`(el) => el.innerText\`
`,
- ),
+ ),
+ sourcePath: zod
+ .string()
+ .optional()
+ .describe(
+ "The absolute or relative path to a JavaScript file on the MCP server's local filesystem. Provide either this or function, but not both.",
+ ),
+ format: zod
+ .enum(['function', 'script'])
+ .optional()
+ .describe(
+ 'How to interpret the source. "function" treats it as a function declaration and supports args. "script" evaluates it as classic JavaScript and does not support args. Defaults to "function". ECMAScript modules are not supported.',
+ ),
args: zod
.array(
zod
@@ -85,18 +102,26 @@ Example with arguments: \`(el) => el.innerText\`
blockedByDialog: true,
verifyFilesSchema: {
filePath: true,
+ sourcePath: true,
},
handler: async (request, response, context) => {
const {
serviceWorkerId,
args: uidArgs,
function: fnString,
+ sourcePath,
+ format = 'function',
pageId,
dialogAction,
filePath,
waitForStableDom,
} = request.params;
+ const source = await resolveScriptSource(fnString, sourcePath, context);
+ if (format === 'script' && uidArgs && uidArgs.length > 0) {
+ throw new Error('args cannot be used when format is "script".');
+ }
+
if (cliArgs.categoryExtensions && serviceWorkerId) {
if (uidArgs && uidArgs.length > 0) {
throw new Error(
@@ -112,7 +137,7 @@ Example with arguments: \`(el) => el.innerText\`
.getSelectedMcpPage()
.waitForEventsAfterAction(
async () => {
- await performEvaluation(worker, fnString, [], response, {
+ await performEvaluation(worker, source, format, [], response, {
filePath,
context,
});
@@ -153,7 +178,7 @@ Example with arguments: \`(el) => el.innerText\`
const result = await mcpPage.waitForEventsAfterAction(
async () => {
- await performEvaluation(evaluatable, fnString, args, response, {
+ await performEvaluation(evaluatable, source, format, args, response, {
filePath,
context,
});
@@ -165,24 +190,63 @@ Example with arguments: \`(el) => el.innerText\`
};
});
+const resolveScriptSource = async (
+ inlineSource: string | undefined,
+ sourcePath: string | undefined,
+ context: Context,
+): Promise<string> => {
+ if (inlineSource !== undefined) {
+ if (sourcePath !== undefined) {
+ throw new Error('Specify exactly one of function or sourcePath.');
+ }
+ return inlineSource;
+ }
+ if (sourcePath === undefined) {
+ throw new Error('Specify exactly one of function or sourcePath.');
+ }
+
+ const resourceUrl = sourcePath.startsWith('file:')
+ ? sourcePath
+ : pathToFileURL(sourcePath).href;
+ try {
+ return await context.loadResource(resourceUrl);
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ throw new Error(
+ `Unable to read script source from ${sourcePath}: ${errorMessage}`,
+ {cause: error},
+ );
+ }
+};
+
const performEvaluation = async (
evaluatable: Evaluatable,
- fnString: string,
+ source: string,
+ format: 'function' | 'script',
args: Array<JSHandle<unknown>>,
response: Response,
- options?: {filePath?: string; context: Context},
+ options: {filePath?: string; context: Context},
) => {
- using fn = await evaluatable.evaluateHandle(`(${fnString})`);
+ let result: string | undefined;
+ if (format === 'function') {
+ const functionSource = source.trimEnd().replace(/;$/, '');
+ using fn = await evaluatable.evaluateHandle<
+ [],
+ () => (...args: unknown[]) => unknown
+ >(`(\n${functionSource}\n)`);
+ result = await evaluatable.evaluate(
+ async (fn, ...args) => {
+ return JSON.stringify(await fn(...args));
+ },
+ fn,
+ ...args,
+ );
+ } else {
+ using value = await evaluatable.evaluateHandle(source);
+ result = await evaluatable.evaluate(value => JSON.stringify(value), value);
+ }
- const result = await evaluatable.evaluate(
- async (fn, ...args) => {
- // @ts-expect-error no types for function fn
- return JSON.stringify(await fn(...args));
- },
- fn,
- ...args,
- );
- if (options?.filePath) {
+ if (options.filePath) {
const data = new TextEncoder().encode(result ?? 'undefined');
const {filename} = await options.context.saveFile(
data,
diff --git a/tests/ToolHandler.test.ts b/tests/ToolHandler.test.ts
index fa835be8..24677d34 100644
--- a/tests/ToolHandler.test.ts
+++ b/tests/ToolHandler.test.ts
@@ -26,6 +26,7 @@ import {
type DevToolsData,
type ToolDefinition,
} from '../src/tools/ToolDefinition.js';
+import {evaluateScript} from '../src/tools/script.js';
import {createTools} from '../src/tools/tools.js';
import {createMockMcpContext} from './mocks.js';
import {getMockBrowser} from './utils.js';
@@ -744,6 +745,39 @@ describe('ToolHandler', () => {
assert.strictEqual(handlerCalled, false);
});
+ it('validates evaluate_script sourcePath before reading the file', async () => {
+ const serverArgs = new ConfigParser('1.0.0', ['node', 'script.js'], {
+ CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS: 'true',
+ }).parse();
+ const tool = evaluateScript(serverArgs);
+ const mockContext = sinon.createStubInstance(McpContext);
+ const mockProcess = sinon.createStubInstance(ChildProcess);
+ mockContext.browser = getMockBrowser({process: mockProcess});
+ mockContext.validatePath.rejects(
+ new Error('Access denied: path is outside roots'),
+ );
+
+ const toolHandler = new ToolHandler(
+ tool,
+ serverArgs,
+ async () => mockContext,
+ new Mutex(),
+ sinon.spy(),
+ sinon.spy(),
+ );
+ const sourcePath = path.resolve('/outside/workspace/script.js');
+
+ const result = await toolHandler.handle({sourcePath});
+
+ assert.strictEqual(result.isError, true);
+ assert.match(
+ result.content[0].type === 'text' ? result.content[0].text : '',
+ /Access denied/,
+ );
+ sinon.assert.calledOnceWithExactly(mockContext.validatePath, sourcePath);
+ sinon.assert.notCalled(mockContext.loadResource);
+ });
+
it('validates verifyFilesSchema when local: true and browser is running locally via process', async () => {
let handlerCalled = false;
let receivedParams: Record<string, unknown> | undefined;
diff --git a/tests/cli.test.ts b/tests/cli.test.ts
index e7f68fed..14a4e3ad 100644
--- a/tests/cli.test.ts
+++ b/tests/cli.test.ts
@@ -1212,6 +1212,16 @@ describe('cli command strings', () => {
assert.strictEqual(command, 'dummy_cmd <arg1> <arg2>');
});
+ it('keeps evaluate_script function as an optional positional', () => {
+ const {command, usage} = buildCommand(
+ 'evaluate_script',
+ commands['evaluate_script'].args,
+ );
+ assert.strictEqual(command, 'evaluate_script [function]');
+ assert.ok(!usage.includes('[--function]'));
+ assert.ok(usage.includes('[--sourcePath]'));
+ });
+
it('lists optional args in the usage line, not the command', () => {
const {command, usage} = buildCommand('dummy_cmd', dummyArgsOptional);
assert.ok(!command.includes('--'));
diff --git a/tests/e2e/chrome-devtools-commands.test.ts b/tests/e2e/chrome-devtools-commands.test.ts
index 862c55ba..bd191227 100644
--- a/tests/e2e/chrome-devtools-commands.test.ts
+++ b/tests/e2e/chrome-devtools-commands.test.ts
@@ -6,11 +6,15 @@
import assert from 'node:assert';
import crypto from 'node:crypto';
+import fs from 'node:fs/promises';
+import path from 'node:path';
import {describe, it, afterEach, beforeEach} from 'node:test';
+import {pathToFileURL} from 'node:url';
import {
assertDaemonIsNotRunning,
assertDaemonIsRunning,
+ createTempDir,
runCli,
} from '../utils.js';
@@ -72,6 +76,91 @@ describe('chrome-devtools', () => {
);
});
+ it('can evaluate inline and local JavaScript', async () => {
+ using rootDirectory = createTempDir('evaluate-script-cli-');
+ const daemonDirectory = path.join(rootDirectory.path, 'daemon');
+ const clientDirectory = path.join(rootDirectory.path, 'client');
+ await fs.mkdir(daemonDirectory);
+ await fs.mkdir(clientDirectory);
+
+ const sourcePath = path.join(clientDirectory, 'script.js');
+ const outputPath = path.join(clientDirectory, 'result.json');
+ try {
+ const startResult = await runCli(['start'], sessionId, {
+ cwd: daemonDirectory,
+ });
+ assert.strictEqual(
+ startResult.status,
+ 0,
+ `start command failed: ${startResult.stderr}`,
+ );
+
+ const inlineResult = await runCli(
+ ['evaluate_script', '() => 6 * 7', '--pageId', '1'],
+ sessionId,
+ {cwd: clientDirectory},
+ );
+ assert.strictEqual(
+ inlineResult.status,
+ 0,
+ `inline evaluation failed: ${inlineResult.stderr}`,
+ );
+ assert.match(inlineResult.stdout, /\b42\b/);
+
+ await fs.writeFile(
+ sourcePath,
+ 'document.title = "Local script"; document.title',
+ 'utf8',
+ );
+ const fileResult = await runCli(
+ [
+ 'evaluate_script',
+ '--pageId',
+ '1',
+ '--sourcePath',
+ sourcePath,
+ '--format',
+ 'script',
+ '--filePath',
+ outputPath,
+ ],
+ sessionId,
+ {cwd: clientDirectory},
+ );
+ assert.strictEqual(
+ fileResult.status,
+ 0,
+ `file evaluation failed: ${fileResult.stderr}`,
+ );
+ assert.strictEqual(
+ JSON.parse(await fs.readFile(outputPath, 'utf8')),
+ 'Local script',
+ );
+
+ const fileUrlResult = await runCli(
+ [
+ 'evaluate_script',
+ '--pageId',
+ '1',
+ '--sourcePath',
+ pathToFileURL(sourcePath).href,
+ '--format',
+ 'script',
+ ],
+ sessionId,
+ {cwd: clientDirectory},
+ );
+ assert.strictEqual(
+ fileUrlResult.status,
+ 0,
+ `file URL evaluation failed: ${fileUrlResult.stderr}`,
+ );
+ assert.match(fileUrlResult.stdout, /Local script/);
+ } finally {
+ await runCli(['stop'], sessionId, {cwd: clientDirectory});
+ }
+ });
+
it('fails to invoke list_network_requests when categoryNetwork is disabled', async () => {
await runCli(['start', '--categoryNetwork=false'], sessionId);
diff --git a/tests/tools/script.test.ts b/tests/tools/script.test.ts
index b6a91f29..d428c8ce 100644
--- a/tests/tools/script.test.ts
+++ b/tests/tools/script.test.ts
@@ -5,13 +5,14 @@
*/
import assert from 'node:assert';
-import path from 'node:path';
import {readFile} from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
import {afterEach, describe, it} from 'node:test';
+import {pathToFileURL} from 'node:url';
import sinon from 'sinon';
-import type {ParsedArguments} from '../../src/config/ConfigParser.js';
import {TextSnapshot} from '../../src/TextSnapshot.js';
import {zod} from '../../src/third_party/index.js';
import {installExtension} from '../../src/tools/extensions.js';
@@ -51,6 +52,182 @@ describe('script', () => {
assert.strictEqual(JSON.parse(lineEvaluation), 10);
});
});
+ it('evaluates an inline classic script', async () => {
+ await withMcpContext(async (response, context, args) => {
+ await evaluateScript(args).handler(
+ {
+ params: {
+ function: 'document.title = "Script title"; document.title',
+ format: 'script',
+ },
+ },
+ response,
+ context,
+ );
+ const lineEvaluation = response.responseLines.at(2);
+ assert.ok(lineEvaluation);
+ assert.strictEqual(JSON.parse(lineEvaluation), 'Script title');
+ });
+ });
+ it('evaluates a function ending with a single-line comment', async () => {
+ await withMcpContext(async (response, context, args) => {
+ await evaluateScript(args).handler(
+ {
+ params: {
+ function: '() => document.title // get title',
+ },
+ },
+ response,
+ context,
+ );
+ const lineEvaluation = response.responseLines.at(2);
+ assert.ok(lineEvaluation);
+ assert.strictEqual(JSON.parse(lineEvaluation), '');
+ });
+ });
+ it('evaluates a function ending with a semicolon', async () => {
+ await withMcpContext(async (response, context, args) => {
+ await evaluateScript(args).handler(
+ {
+ params: {
+ function: '() => document.title;',
+ },
+ },
+ response,
+ context,
+ );
+ const lineEvaluation = response.responseLines.at(2);
+ assert.ok(lineEvaluation);
+ assert.strictEqual(JSON.parse(lineEvaluation), '');
+ });
+ });
+ it('does not execute multi-statement source in function mode', async () => {
+ await withMcpContext(async (response, context, args) => {
+ await assert.rejects(
+ evaluateScript(args).handler(
+ {
+ params: {
+ function: '() => document.title; document.title = "unexpected"',
+ },
+ },
+ response,
+ context,
+ ),
+ );
+ assert.strictEqual(
+ await context.getSelectedMcpPage().pptrPage.title(),
+ '',
+ );
+ });
+ });
+ it('serializes script results inside the browser', async () => {
+ await withMcpContext(async (response, context, args) => {
+ await evaluateScript(args).handler(
+ {
+ params: {
+ function: 'new URL("https://example.com/path")',
+ format: 'script',
+ },
+ },
+ response,
+ context,
+ );
+ const lineEvaluation = response.responseLines.at(2);
+ assert.ok(lineEvaluation);
+ assert.strictEqual(
+ JSON.parse(lineEvaluation),
+ 'https://example.com/path',
+ );
+ });
+ });
+ it('loads function source from a local file', async () => {
+ const {page, response, context, args} = createHandlerMocks();
+ const sourcePath = path.join(os.tmpdir(), 'function.js');
+ context.loadResource.resolves('() => document.title;');
+
+ await evaluateScript(args).handler(
+ {params: {sourcePath}},
+ response,
+ context,
+ );
+
+ sinon.assert.calledOnceWithExactly(
+ context.loadResource,
+ pathToFileURL(sourcePath).href,
+ );
+ sinon.assert.calledOnce(page.waitForEventsAfterAction);
+ });
+ it('loads classic script source from a file URL', async () => {
+ const {page, response, context, args} = createHandlerMocks();
+ const sourcePath = pathToFileURL(
+ path.join(os.tmpdir(), 'script.js'),
+ ).href;
+ context.loadResource.resolves(
+ 'document.body.dataset.source = "file"; document.body.dataset.source',
+ );
+
+ await evaluateScript(args).handler(
+ {params: {sourcePath, format: 'script'}},
+ response,
+ context,
+ );
+
+ sinon.assert.calledOnceWithExactly(context.loadResource, sourcePath);
+ sinon.assert.calledOnce(page.waitForEventsAfterAction);
+ });
+ it('requires exactly one script source', async () => {
+ const {response, context, args} = createHandlerMocks();
+ await assert.rejects(
+ evaluateScript(args).handler({params: {}}, response, context),
+ /Specify exactly one of function or sourcePath/,
+ );
+ await assert.rejects(
+ evaluateScript(args).handler(
+ {
+ params: {
+ function: '() => true',
+ sourcePath: 'script.js',
+ },
+ },
+ response,
+ context,
+ ),
+ /Specify exactly one of function or sourcePath/,
+ );
+ });
+ it('rejects args for classic scripts', async () => {
+ const {response, context, args} = createHandlerMocks();
+ await assert.rejects(
+ evaluateScript(args).handler(
+ {
+ params: {
+ function: 'document.title',
+ format: 'script',
+ args: ['1_1'],
+ },
+ },
+ response,
+ context,
+ ),
+ /args cannot be used when format is "script"/,
+ );
+ });
+ it('reports unreadable source files', async () => {
+ const {response, context, args} = createHandlerMocks();
+ const sourcePath = path.join(
+ os.tmpdir(),
+ 'missing-evaluate-script-source.js',
+ );
+ context.loadResource.rejects(new Error('File not found'));
+ await assert.rejects(
+ evaluateScript(args).handler({params: {sourcePath}}, response, context),
+ /Unable to read script source.*File not found/,
+ );
+ sinon.assert.calledOnceWithExactly(
+ context.loadResource,
+ pathToFileURL(sourcePath).href,
+ );
+ });
it('skips the stable DOM wait when waitForStableDom is false', async () => {
await withMcpContext(async (response, context, args) => {
const spy = sinon.spy(WaitForHelper.prototype, 'waitForStableDom');
@@ -367,9 +544,8 @@ describe('script', () => {
await context.triggerExtensionAction(extensionId);
response.resetResponseLineForTesting();
- await evaluateScript({
- categoryExtensions: true,
- } as ParsedArguments).handler(
+ const extensionEvaluateScript = evaluateScript(args);
+ await extensionEvaluateScript.handler(
{
params: {
function: String(() => {
@@ -384,6 +560,24 @@ describe('script', () => {
const lineEvaluation = response.responseLines.at(2)!;
assert.strictEqual(JSON.parse(lineEvaluation), 'has-chrome');
+
+ response.resetResponseLineForTesting();
+ await extensionEvaluateScript.handler(
+ {
+ params: {
+ function:
+ '"chrome" in globalThis ? "has-chrome-script" : "no-chrome"',
+ format: 'script',
+ serviceWorkerId: swId,
+ },
+ },
+ response,
+ context,
+ );
+ const scriptEvaluation = response.responseLines.at(2);
+ assert.ok(scriptEvaluation);
+ assert.strictEqual(JSON.parse(scriptEvaluation), 'has-chrome-script');
+
await context.uninstallExtension(extensionId);
const targets = context.browser.targets();
assertNoServiceWorkerReported(targets, extensionId);
@@ -482,10 +676,11 @@ describe('script', () => {
});
it('makes pageId optional in schema when categoryExtensions is true and pageIdRouting is true', () => {
- const tool = evaluateScript({
+ const args = createMockParsedArguments({
categoryExtensions: true,
pageIdRouting: true,
- } as ParsedArguments);
+ });
+ const tool = evaluateScript(args);
const schema = zod.object(tool.schema);
const validSw = schema.safeParse({
function: '() => 1',
@@ -501,9 +696,10 @@ describe('script', () => {
});
it('makes pageId required in schema when categoryExtensions is false and pageIdRouting is true', () => {
- const tool = evaluateScript({
+ const args = createMockParsedArguments({
pageIdRouting: true,
- } as ParsedArguments);
+ });
+ const tool = evaluateScript(args);
const schema = zod.object(tool.schema);
const resultWithoutPageId = schema.safeParse({
function: '() => 1',
diff --git a/tests/utils.ts b/tests/utils.ts
index 2a657a51..6f7bbea2 100644
--- a/tests/utils.ts
+++ b/tests/utils.ts
@@ -425,6 +425,7 @@ export const CLI_PATH = path.resolve('build/src/bin/chrome-devtools.js');
export async function runCli(
args: string[],
sessionId?: string,
+ options?: {cwd?: string},
): Promise<{status: number | null; stdout: string; stderr: string}> {
return new Promise((resolve, reject) => {
const finalArgs = [...args];
@@ -433,6 +434,7 @@ export async function runCli(
}
const child = spawn('node', [CLI_PATH, ...finalArgs], {
env: process.env,
+ cwd: options?.cwd,
});
let stdout = '';
let stderr = '';