Docs Packages

@procedures/browser

packages/browser/README.md on GitHub · Package map · Procedures

npm install @procedures/browser

This package finds a Chromium browser that is already on the host: Microsoft Edge, Google Chrome or Chromium. It renders a page with that browser: a PDF file or a screenshot. The package does not download a browser. It also finds and reads the bookmarks files of the profiles of Chrome, Edge and Chromium.

Each render uses one headless run. The run starts the browser one time, with argv, in a new temporary folder with its own profile. The renders give only their flags and the check of their file.

The package has no procedures. The procedure pdf.render is in @procedures/pdf.

A screenshot#

import { renderScreenshot } from "@procedures/browser";

const { path, bytes, format } = await renderScreenshot({
  url: "https://example.com/",
  output: "example.jpg",
  size: { width: 1280, height: 800 },
});
  • Give one of url, html and file. The address of url starts with http:, https: or file:. The function refuses other addresses.
  • The format is PNG, JPEG or WebP. The extension of output sets the format: .png, .jpg, .jpeg or .webp. Without output, the option format sets it, and the default is PNG.
  • The option format and the extension of output must agree. Otherwise the function gives an error before it starts the browser.
  • The default size of the window is 1280 by 800 CSS pixels. Each side is an integer from 1 to 16384.
  • The option budget gives the scripts and the timers of the page more virtual time before the picture, in milliseconds. Without it, the picture follows the load event.
  • The page can load each address that it names. Give an address that you trust, or a page of your own.

A screenshot as bytes#

import { renderScreenshotBytes } from "@procedures/browser";

const { data, format } = await renderScreenshotBytes({ url: "https://example.com/", format: "jpeg" });
const picture = `data:image/jpeg;base64,${Buffer.from(data).toString("base64")}`;
  • renderScreenshotBytes has the options and the errors of renderScreenshot, with no output. It gives the picture as a Uint8Array.
  • The function writes the picture to a new temporary folder, and reads it. Then it removes the folder, also after an error.
  • The option folder sets the folder that gets the temporary folder. The default is the temporary folder of the system.

A PDF file#

import { renderPdf } from "@procedures/browser";

const { path, bytes } = await renderPdf({ html: "<h1>Menu</h1><p>Soup of the day</p>", output: "menu.pdf" });
  • Give html or file, not the two.
  • After the print, the function examines the file. A file that does not start with %PDF gives an error.

The page count of a PDF file#

import { readFileSync } from "node:fs";
import { pdfPageCount, renderPdf } from "@procedures/browser";

const { path } = await renderPdf({ file: "binder.html" });
const pages = pdfPageCount(readFileSync(path));
  • pdfPageCount(bytes) reads the page tree of the last trailer. The count of a file with incremental updates is the count of its last version.
  • It reads the plain objects, and the object streams with no filter or with the filter /FlateDecode. It does not decrypt.
  • A damaged object does not stop the read.
  • The time and the memory of the read grow linearly with the size of the file. A damaged file that needs a longer scan gives an error.
  • Data that is not a PDF file, or a file with no page tree that it can read, gives an error.

Many pages with one browser#

Each renderPdf call starts a new browser. A browser session starts one browser for many pages. Each page opens in a new tab over the Chrome DevTools Protocol, and the tab closes after its file.

import { withBrowserSession } from "@procedures/browser";

await withBrowserSession({ timeout: 60_000 }, async (session) => {
  for (const [index, html] of pages.entries()) await session.printPdf({ html }, `binder/page-${index}.pdf`);
  console.log(session.launches); // 1
});
  • openBrowserSession(options) starts the browser, and gives the session. withBrowserSession(options, use) also closes the session after use, also when use throws.
  • The options are executable, env, args, timeout, signal and folder. The search of the browser is the search of findBrowser.
  • session.printPdf(source, output, options) prints one page. The source is { file }, { html } or { url }. The address of url starts with http:, https: or file:.
  • The print has the settings of renderPdf: no header and no footer, the page size of the CSS, and the backgrounds.
  • The PDF file comes as a stream in parts of 1 MB, so a large file does not make one large message.
  • A file that does not start with %PDF gives an error. An existing output file changes only after the check of the new file.
  • session.screenshot(source, output, options) takes a picture of the window. The options format and size are as for renderScreenshot.
  • The timeout of the session is the time limit of each page. A page can give its own timeout and signal. At the limit, the tab closes, and the next page can start.
  • When the signal of the session aborts, the session closes. A crash of the browser gives its error to each pending page and each next page.
  • session.launches is the number of browsers that the session started. It is 1.
  • session.close() stops the browser and its process tree, and removes the temporary profile.
  • The browser starts with the flag --remote-debugging-pipe, so the session uses no network port. sessionArgs(profile, extra) gives the argv.
  • The session has no option hostPolicy. For a page that you do not trust, use renderScreenshot or renderPdf with hostPolicy.

The options of each render#

OptionWhat it does
outputThe path of the file. The default is a file in a new temporary folder. The caller moves or deletes it.
executableThe browser program. When it is set, the search does not occur.
argsMore flags for the browser, after the default flags. A browser that runs as root, for example in a container, needs ["--no-sandbox"].
timeoutThe time limit, in milliseconds. The default is 60000.
signalWhen the signal aborts, the browser stops.
runnerThe function that runs the browser. The default is runCommand of @procedures/shell. The tests give their own.
hostPolicyThe host policy of each request of the browser, from @procedures/http. The section The host policy tells more.
onHostRefusalThis function gets each request that the host policy refused. It needs hostPolicy.
  • The browser starts through runCommand of @procedures/shell, not through a shell. At the time limit, or when the signal aborts, runCommand stops the process tree of the browser.
  • The temporary profile keeps the render apart from a browser that the user has open.
  • A missing file, an empty file or a file of the wrong kind gives an error.
  • An existing output file changes only after the check of the new file. Thus a failed render keeps an old output file.
  • Each render removes its temporary page and profile, also after an error. For a file that Windows holds, the removal tries again 3 times.

The host policy#

A check of the address before the render is not enough. A redirect, a resource of the page or a second DNS answer can reach a local address. The option hostPolicy applies the policy to each request of the browser.

import { createHostPolicy } from "@procedures/http";
import { renderScreenshotBytes } from "@procedures/browser";

const { data } = await renderScreenshotBytes({
  url: "https://news.example/",
  format: "jpeg",
  hostPolicy: createHostPolicy({ allow: ["cdn.intranet.example"] }),
  onHostRefusal: (refusal) => console.warn(refusal.method, refusal.target, refusal.reason),
});
  • The run starts the policy proxy of @procedures/http (startPolicyProxy) before the browser. The proxy stops at the end of the run, also after an error.
  • The proxy gives the status 403 to each host that the policy refuses. The browser shows an error for that request.
  • DEFAULT_HOST_POLICY of @procedures/http lets the browser reach each public host, and no other host.
  • The option applies to each render: the screenshot and the PDF file.
  • A Chrome or Edge policy of the computer (ProxySettings or ProxyMode) replaces the flag --proxy-server, and the browser gives no error. Thus the run counts the requests of the proxy.
  • When the page is an http: or https: URL and the proxy gets no request, the render fails. The page of an html or file source can have no request, so this check does not apply to it.

policyProxyArgs(proxyUrl) gives the flags of the browser. They come before the flags of args:

FlagWhat it does
--proxy-server=<url of the proxy>The browser sends each http:, https:, ws: and wss: request to the proxy. The proxy resolves the names, not the browser.
--proxy-bypass-list=<-loopback>The browser also sends the requests for localhost, the loopback addresses and the link-local addresses to the proxy.
--disable-quicThe browser does not use QUIC, so no request goes over UDP around the proxy.
--force-webrtc-ip-handling-policy=disable_non_proxied_udpWebRTC does not use UDP, and does not show a local address.
--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1The browser does no DNS look-up. The only exception is the address of the proxy.
  • With hostPolicy, args cannot have a flag that can undo these flags. The run gives an error before it starts the browser.
  • These flags are --proxy-server, --proxy-bypass-list, --no-proxy-server, --proxy-pac-url, --proxy-auto-detect, --use-system-proxy-resolver and --winhttp-proxy-resolver.
  • The other flags are --enable-quic, --origin-to-force-quic-on, --force-webrtc-ip-handling-policy, --host-resolver-rules and --host-rules.
  • The check finds a flag with the prefix --, - or /, and ignores the letter case.
  • WebTransport fails through a proxy, so a page cannot use it.
  • The sources of the flags are the Chromium documents net/docs/proxy.md, chrome_switches.h, network_switch_list.h, network_switches.cc, content_switches.cc and webrtc_ip_handling_policy.h.

The browser#

findBrowser(options) gives the path of the browser program, or undefined. The search uses the first of these:

  1. The option executable.
  2. The environment variable PDF_BROWSER, then CHROME_PATH.
  3. On Windows: Chrome and Chromium, then Edge, in Program Files, Program Files (x86) and LOCALAPPDATA. Edge 158 on Windows makes no PDF file (issue client#756).
  4. On macOS: the app bundles of Chrome, Edge and Chromium in /Applications and ~/Applications.
  5. The PATH: google-chrome, google-chrome-stable, chromium, chromium-browser, microsoft-edge and microsoft-edge-stable. On Windows, chrome.exe and msedge.exe.

When the search finds no browser, each render gives an error that names PDF_BROWSER. The name comes from @procedures/pdf, the first home of the search.

The bookmarks of the profiles#

import { homedir } from "node:os";
import { browserDataFolders, findBookmarkFiles, readBookmarkFile } from "@procedures/browser";

const files = await findBookmarkFiles(browserDataFolders(process.platform, process.env, homedir()));
for (const file of files) console.log(file.id, file.browser, file.name, file.kind, file.size);
const first = files[0] === undefined ? undefined : await readBookmarkFile(files[0]);
  • browserDataFolders(platform, env, home, browsers) gives the folder of the user data of each browser on Windows, macOS and Linux. It reads no file.
  • The browsers are chrome, edge and chromium (PROFILE_BROWSERS), the browsers that findBrowser finds. The argument browsers selects some of them.
  • findBookmarkFiles(folders, files) finds the files Bookmarks and AccountBookmarks of each profile. It reads the names of the profiles from the file Local State. Each folder has the key of its browser, so a caller can add the folder of another Chromium browser.
  • The files come in the order of the folders. In a folder, Default comes first, then Profile <n> by the number. The guest and system profiles have no bookmarks.
  • The id of a file is <browser>:<profile folder>:<file name>, for example edge:Default:Bookmarks. The files of two browsers have different ids. A host can give the id and the name to a page, and keep the path.
  • Each file has its path and its size in bytes at the time of the search.
  • readBookmarkFile(file, files, options) reads and parses a file. It reads the size again, and refuses a file over MAX_BOOKMARKS_BYTES before the read. The default prefix of the keys is the id of the file and a colon.
  • The argument files is the file access. The default is diskFileAccess. A test gives files in memory.
  • diskFileAccess.list gives no names for each error: a missing folder, and also a folder that it cannot read (EACCES).

parseChromeBookmarks(value, options) reads the JSON of a bookmarks file. Chrome, Edge and Chromium write the same format. The parser gives the root folders, each with its folders and its sites.

  • Each site has its address, its title, the time when the user added it, and the names of its folders as path.
  • The parser keeps only the http and https addresses. The count skipped tells how many other bookmarks the file has.
  • A part that the parser cannot read gives a problem in problems. The parser reads the other parts.
  • The key of a folder is its guid, else its id, else its place in the file. The place is the name of its root and the index of each child. Thus each folder of a file has a different key.
  • The option prefix goes before each key of a folder. Give two files different prefixes, so that their keys are different.
  • The roots of Chrome come first. The roots with other names come after them, in the order of their code units. Thus each runtime gives the same parse.
  • The parser reads 100 folders deep at most (MAX_BOOKMARK_DEPTH). A deeper folder gives a problem.
  • A value with no object roots is not a bookmarks file. Then the parser throws.
  • MAX_BOOKMARKS_BYTES is the largest bookmarks file: 64 MB. readBookmarkFile applies it. A page that reads a file of its own examines the size before the read.

The entry for a page#

The entry @procedures/browser/bookmarks imports no Node built-in, so a page can use it. It has the parser and its types, not the search.

import { parseChromeBookmarks, type ChromeBookmarks } from "@procedures/browser/bookmarks";

const read: ChromeBookmarks = parseChromeBookmarks(JSON.parse(await chosenFile.text()), { prefix: "file:1:" });

The other functions#

  • browserCandidates(platform, env) gives the paths that the search examines.
  • pdfArgs(page, output, profile, extra) gives the argv of a print.
  • screenshotArgs(page, output, profile, size, budget, extra) gives the argv of a screenshot.
  • screenshotFormatOf(output, format) gives the format of a screenshot.
  • isPdfFile(path) tells if a file starts with %PDF.
  • isImageFile(path, format) tells if a file starts with the signature of a PNG, JPEG or WebP file.
  • chromeTime(value) gives the ISO 8601 time of a Chrome time: a text of the microseconds from 1601-01-01.
  • profileNames(localState) gives the name of each profile from the JSON of the file Local State.