forked from ChromeDevTools/chrome-devtools-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscreenshot.ts
More file actions
346 lines (312 loc) · 11.2 KB
/
screenshot.ts
File metadata and controls
346 lines (312 loc) · 11.2 KB
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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {zod} from '../third_party/index.js';
import type {ElementHandle, Page} from '../third_party/index.js';
import {ToolCategory} from './categories.js';
import {defineTool} from './ToolDefinition.js';
/**
* Takes a full-page screenshot of an iframe's content by temporarily
* expanding the iframe to show all scrollable content.
*/
async function takeIframeFullPageScreenshot(
iframeHandle: ElementHandle<Element>,
options: {type: 'png' | 'jpeg' | 'webp'; quality?: number},
): Promise<Uint8Array> {
const contentFrame = await iframeHandle.contentFrame();
if (!contentFrame) {
throw new Error(
'The specified element is not an iframe or its content is not accessible.',
);
}
// Get the full scroll dimensions of the iframe content
const {scrollWidth, scrollHeight} = await contentFrame.evaluate(() => {
return {
scrollWidth: document.documentElement.scrollWidth,
scrollHeight: document.documentElement.scrollHeight,
};
});
// Get the original iframe styles to restore later
const originalIframeStyle = await iframeHandle.evaluate(el => {
const iframe = el as HTMLIFrameElement;
return {
width: iframe.style.width,
height: iframe.style.height,
maxWidth: iframe.style.maxWidth,
maxHeight: iframe.style.maxHeight,
position: iframe.style.position,
};
});
// Get the original iframe content styles to restore later
const originalContentStyle = await contentFrame.evaluate(() => {
return {
htmlHeight: document.documentElement.style.height,
htmlOverflow: document.documentElement.style.overflow,
bodyHeight: document.body.style.height,
bodyOverflow: document.body.style.overflow,
};
});
try {
// Temporarily expand the iframe to show all content
// Setting position:absolute helps escape flex/grid layout constraints
await iframeHandle.evaluate(
(el, dims) => {
const iframe = el as HTMLIFrameElement;
iframe.style.width = `${dims.scrollWidth}px`;
iframe.style.height = `${dims.scrollHeight}px`;
iframe.style.maxWidth = 'none';
iframe.style.maxHeight = 'none';
iframe.style.position = 'absolute';
},
{scrollWidth, scrollHeight},
);
// Set overflow:visible on iframe content to allow content to expand
await contentFrame.evaluate(dims => {
document.documentElement.style.height = `${dims.scrollHeight}px`;
document.documentElement.style.overflow = 'visible';
document.body.style.height = `${dims.scrollHeight}px`;
document.body.style.overflow = 'visible';
}, {scrollHeight});
// Scroll to top-left to ensure we capture from the beginning
await contentFrame.evaluate(() => {
window.scrollTo(0, 0);
});
// Small delay to allow the iframe to resize and render
await new Promise(resolve => setTimeout(resolve, 150));
// Take screenshot of the expanded iframe
const screenshot = await iframeHandle.screenshot({
type: options.type,
quality: options.quality,
optimizeForSpeed: true,
});
return screenshot;
} finally {
// Restore original iframe content styles
await contentFrame.evaluate(style => {
document.documentElement.style.height = style.htmlHeight;
document.documentElement.style.overflow = style.htmlOverflow;
document.body.style.height = style.bodyHeight;
document.body.style.overflow = style.bodyOverflow;
}, originalContentStyle);
// Restore original iframe styles
await iframeHandle.evaluate(
(el, style) => {
const iframe = el as HTMLIFrameElement;
iframe.style.width = style.width;
iframe.style.height = style.height;
iframe.style.maxWidth = style.maxWidth;
iframe.style.maxHeight = style.maxHeight;
iframe.style.position = style.position;
},
originalIframeStyle,
);
}
}
/**
* Finds the main content iframe on the page if one exists.
* Returns the iframe element handle if found, null otherwise.
*/
async function findMainContentIframe(
page: Page,
): Promise<ElementHandle<Element> | null> {
// Look for iframes that take up a significant portion of the viewport
const iframeHandle = await page.evaluateHandle(() => {
const iframes = Array.from(document.querySelectorAll('iframe'));
if (iframes.length === 0) return null;
// Find the largest iframe that has scrollable content
let bestIframe: HTMLIFrameElement | null = null;
let bestScore = 0;
for (let i = 0; i < iframes.length; i++) {
const iframe = iframes[i]!;
try {
const rect = iframe.getBoundingClientRect();
const contentDoc = iframe.contentDocument;
// Skip tiny iframes or iframes we can't access
if (rect.width < 100 || rect.height < 100 || !contentDoc) continue;
// Calculate score based on size and scrollable content
const scrollHeight = contentDoc.documentElement.scrollHeight;
const hasScrollableContent = scrollHeight > rect.height;
const areaScore = rect.width * rect.height;
const scrollScore = hasScrollableContent ? scrollHeight : 0;
const score = areaScore + scrollScore * 100;
if (score > bestScore) {
bestScore = score;
bestIframe = iframe;
}
} catch {
// Skip iframes we can't access (cross-origin)
continue;
}
}
return bestIframe;
});
const iframeElement = iframeHandle.asElement();
if (!iframeElement) {
await iframeHandle.dispose();
return null;
}
// Cast to the correct type
const iframe = iframeElement as ElementHandle<Element>;
// Verify the iframe has scrollable content
const contentFrame = await iframe.contentFrame();
if (!contentFrame) {
await iframe.dispose();
return null;
}
const {scrollHeight, clientHeight} = await contentFrame.evaluate(() => ({
scrollHeight: document.documentElement.scrollHeight,
clientHeight: document.documentElement.clientHeight,
}));
// Only return if there's actually scrollable content
if (scrollHeight > clientHeight) {
return iframe;
}
await iframe.dispose();
return null;
}
export const screenshot = defineTool({
name: 'take_screenshot',
description: `Take a screenshot of the page or element.`,
annotations: {
category: ToolCategory.DEBUGGING,
// Not read-only due to filePath param.
readOnlyHint: false,
},
schema: {
format: zod
.enum(['png', 'jpeg', 'webp'])
.default('png')
.describe('Type of format to save the screenshot as. Default is "png"'),
quality: zod
.number()
.min(0)
.max(100)
.optional()
.describe(
'Compression quality for JPEG and WebP formats (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format.',
),
uid: zod
.string()
.optional()
.describe(
'The uid of an element on the page from the page content snapshot. If omitted takes a pages screenshot.',
),
fullPage: zod
.boolean()
.optional()
.describe(
'If set to true takes a screenshot of the full page instead of the currently visible viewport. Incompatible with uid unless iframeUid is also provided.',
),
iframeUid: zod
.string()
.optional()
.describe(
'The uid of an iframe element. When used with fullPage=true, captures the full scrollable content of the iframe by temporarily expanding it.',
),
filePath: zod
.string()
.optional()
.describe(
'The absolute path, or a path relative to the current working directory, to save the screenshot to instead of attaching it to the response.',
),
},
handler: async (request, response, context) => {
const {uid, fullPage, iframeUid} = request.params;
// Validate parameter combinations
if (uid && fullPage && !iframeUid) {
throw new Error('Providing both "uid" and "fullPage" is not allowed.');
}
if (uid && iframeUid) {
throw new Error('Providing both "uid" and "iframeUid" is not allowed.');
}
if (iframeUid && !fullPage) {
throw new Error(
'iframeUid requires fullPage=true to capture the full iframe content.',
);
}
const format = request.params.format;
const quality = format === 'png' ? undefined : request.params.quality;
let screenshot: Uint8Array;
let responseMessage: string;
if (iframeUid && fullPage) {
// Full-page screenshot of iframe content (explicit iframe specified)
const iframeHandle = await context.getElementByUid(iframeUid);
try {
screenshot = await takeIframeFullPageScreenshot(iframeHandle, {
type: format,
quality,
});
responseMessage = `Took a full-page screenshot of iframe with uid "${iframeUid}".`;
} finally {
void iframeHandle.dispose();
}
} else if (uid) {
// Screenshot of a specific element
const handle = await context.getElementByUid(uid);
try {
screenshot = await handle.screenshot({
type: format,
quality,
optimizeForSpeed: true,
});
responseMessage = `Took a screenshot of node with uid "${uid}".`;
} finally {
void handle.dispose();
}
} else if (fullPage) {
// Full-page screenshot - auto-detect iframe with scrollable content
const page: Page = context.getSelectedPage();
const mainIframe = await findMainContentIframe(page);
if (mainIframe) {
// Found an iframe with scrollable content - capture its full content
try {
screenshot = await takeIframeFullPageScreenshot(mainIframe, {
type: format,
quality,
});
responseMessage =
'Took a full-page screenshot of the main content iframe.';
} finally {
void mainIframe.dispose();
}
} else {
// No significant iframe found - take regular full page screenshot
screenshot = await page.screenshot({
type: format,
fullPage: true,
quality,
optimizeForSpeed: true,
});
responseMessage = 'Took a screenshot of the full current page.';
}
} else {
// Viewport screenshot
const page: Page = context.getSelectedPage();
screenshot = await page.screenshot({
type: format,
fullPage: false,
quality,
optimizeForSpeed: true,
});
responseMessage = "Took a screenshot of the current page's viewport.";
}
response.appendResponseLine(responseMessage);
if (request.params.filePath) {
const file = await context.saveFile(screenshot, request.params.filePath);
response.appendResponseLine(`Saved screenshot to ${file.filename}.`);
} else if (screenshot.length >= 2_000_000) {
const {filename} = await context.saveTemporaryFile(
screenshot,
`image/${request.params.format}`,
);
response.appendResponseLine(`Saved screenshot to ${filename}.`);
} else {
response.attachImage({
mimeType: `image/${request.params.format}`,
data: Buffer.from(screenshot).toString('base64'),
});
}
},
});