Docs Packages
@procedures/browser
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,htmlandfile. The address ofurlstarts withhttp:,https:orfile:. The function refuses other addresses. - The format is PNG, JPEG or WebP. The extension of
outputsets the format:.png,.jpg,.jpegor.webp. Withoutoutput, the optionformatsets it, and the default is PNG. - The option
formatand the extension ofoutputmust 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
budgetgives 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")}`;
renderScreenshotByteshas the options and the errors ofrenderScreenshot, with nooutput. It gives the picture as aUint8Array.- The function writes the picture to a new temporary folder, and reads it. Then it removes the folder, also after an error.
- The option
foldersets 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
htmlorfile, not the two. - After the print, the function examines the file. A file that does not start with
%PDFgives 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 afteruse, also whenusethrows.- The options are
executable,env,args,timeout,signalandfolder. The search of the browser is the search offindBrowser. session.printPdf(source, output, options)prints one page. The source is{ file },{ html }or{ url }. The address ofurlstarts withhttp:,https:orfile:.- 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
%PDFgives 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 optionsformatandsizeare as forrenderScreenshot.- The
timeoutof the session is the time limit of each page. A page can give its owntimeoutandsignal. At the limit, the tab closes, and the next page can start. - When the
signalof the session aborts, the session closes. A crash of the browser gives its error to each pending page and each next page. session.launchesis 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, userenderScreenshotorrenderPdfwithhostPolicy.
The options of each render#
| Option | What it does |
|---|---|
output | The path of the file. The default is a file in a new temporary folder. The caller moves or deletes it. |
executable | The browser program. When it is set, the search does not occur. |
args | More flags for the browser, after the default flags. A browser that runs as root, for example in a container, needs ["--no-sandbox"]. |
timeout | The time limit, in milliseconds. The default is 60000. |
signal | When the signal aborts, the browser stops. |
runner | The function that runs the browser. The default is runCommand of @procedures/shell. The tests give their own. |
hostPolicy | The host policy of each request of the browser, from @procedures/http. The section The host policy tells more. |
onHostRefusal | This function gets each request that the host policy refused. It needs hostPolicy. |
- The browser starts through
runCommandof@procedures/shell, not through a shell. At the time limit, or when the signal aborts,runCommandstops 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_POLICYof@procedures/httplets 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 (
ProxySettingsorProxyMode) 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:orhttps:URL and the proxy gets no request, the render fails. The page of anhtmlorfilesource 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:
| Flag | What 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-quic | The browser does not use QUIC, so no request goes over UDP around the proxy. |
--force-webrtc-ip-handling-policy=disable_non_proxied_udp | WebRTC does not use UDP, and does not show a local address. |
--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1 | The browser does no DNS look-up. The only exception is the address of the proxy. |
- With
hostPolicy,argscannot 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-resolverand--winhttp-proxy-resolver. - The other flags are
--enable-quic,--origin-to-force-quic-on,--force-webrtc-ip-handling-policy,--host-resolver-rulesand--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.ccandwebrtc_ip_handling_policy.h.
The browser#
findBrowser(options) gives the path of the browser program, or undefined. The search uses the first of these:
- The option
executable. - The environment variable
PDF_BROWSER, thenCHROME_PATH. - On Windows: Chrome and Chromium, then Edge, in
Program Files,Program Files (x86)andLOCALAPPDATA. Edge 158 on Windows makes no PDF file (issue client#756). - On macOS: the app bundles of Chrome, Edge and Chromium in
/Applicationsand~/Applications. - The
PATH:google-chrome,google-chrome-stable,chromium,chromium-browser,microsoft-edgeandmicrosoft-edge-stable. On Windows,chrome.exeandmsedge.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,edgeandchromium(PROFILE_BROWSERS), the browsers thatfindBrowserfinds. The argumentbrowsersselects some of them. findBookmarkFiles(folders, files)finds the filesBookmarksandAccountBookmarksof each profile. It reads the names of the profiles from the fileLocal 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,
Defaultcomes first, thenProfile <n>by the number. The guest and system profiles have no bookmarks. - The id of a file is
<browser>:<profile folder>:<file name>, for exampleedge: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
pathand itssizein 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 overMAX_BOOKMARKS_BYTESbefore the read. The default prefix of the keys is the id of the file and a colon.- The argument
filesis the file access. The default isdiskFileAccess. A test gives files in memory. diskFileAccess.listgives 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
httpandhttpsaddresses. The countskippedtells 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 itsid, 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
prefixgoes 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
rootsis not a bookmarks file. Then the parser throws. MAX_BOOKMARKS_BYTESis the largest bookmarks file: 64 MB.readBookmarkFileapplies 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 fileLocal State.