Skip to content

withDom

Runs fn with a headless DOM installed, tearing it down afterward even if fn throws. The DomEnv is passed to fn for access to window/document.

installDom with the cleanup handled for you: the callback receives the environment, its return value is passed through, and teardown() runs in a finally, so an exception inside the callback cannot leave browser globals behind. Node only; the snippet is not executed here.

import {withDom} from "@d3plus/ssr";
const html = await withDom({}, async ({document}) => {
const table = document.createElement("table");
table.innerHTML = "<tr><td>built headlessly</td></tr>";
return table.outerHTML;
});
// The headless DOM is torn down here, whether the callback returned or threw.
// Options are the same as installDom's: pass your own window, or custom HTML.
await withDom({html: "<!doctype html><html lang='es'><body></body></html>"}, async env => {
// …
});

Parameters

import {withDom} from "@d3plus/ssr";
optsrequiredDomEnvOptions
fnrequiredFunction