0

Get Screenshot

by
Published today

Take a PNG screenshot of a page (url or raw html), returned base64-encoded so Windmill previews it. Extra fields go in options (gotoOptions, viewport, waitForSelector, userAgent, ...).

Script cloudflare Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 3 hours ago
1
//native
2

3
/**
4
 * Get Screenshot
5
 * Take a PNG screenshot of a page (url or raw html), returned base64-encoded so Windmill previews it. Extra fields go in options (gotoOptions, viewport, waitForSelector, userAgent, ...).
6
 */
7
export async function main(
8
  auth: RT.Cloudflare,
9
  url: string | undefined,
10
  html: string | undefined,
11
  full_page: boolean | undefined,
12
  options: { [key: string]: any } | undefined
13
) {
14
  if (!url && !html) throw new Error("Either url or html is required")
15

16
  const response = await fetch(
17
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/browser-rendering/screenshot`,
18
    {
19
      method: "POST",
20
      headers: {
21
        Authorization: `Bearer ${auth.token}`,
22
        "Content-Type": "application/json",
23
      },
24
      body: JSON.stringify({
25
        url: url || undefined,
26
        html: html || undefined,
27
        screenshotOptions: { fullPage: full_page ?? undefined },
28
        ...options,
29
      }),
30
    }
31
  )
32

33
  if (!response.ok) {
34
    throw new Error(`${response.status} ${await response.text()}`)
35
  }
36

37
  const bytes = new Uint8Array(await response.arrayBuffer())
38
  let binary = ""
39
  for (let i = 0; i < bytes.length; i += 0x8000) {
40
    binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
41
  }
42
  // Windmill renders { png: <base64> } inline in the result panel.
43
  return { png: btoa(binary) }
44
}
45