SnapDOM Plugins
Plugins turn a capture into HTML, structured context, element maps, PDFs or recordings. Write hooks when you need to change the captured content or add an output.
A plugin is a plain object with a unique name and lifecycle hooks. Capture hooks can change the cloned content; defineExports adds methods to the result. Hooks may be synchronous or async. The core exports images, canvas and blobs; see the plugin catalogue for other outputs.
Official plugins
| Package | Outputs | Reference and demos |
|---|---|---|
| @zumer/snapdom-plugins | HTML, structured context, element maps, effects and recordings. | Plugin toolbox |
| @zumer/snapdom-pdf | Searchable, paginated PDF with selectable text, links and optional form fields. | |
| @zumer/snapdom-vector | Editable SVG and Figma clipboard export. | Vector |
| @zumer/snapdom-stream | A live element as a canvas, for WebGL textures and video overlays. | Stream |
Install the toolbox alongside SnapDOM 3.4.0 or newer (plugins 5.x):
npm install @zumer/snapdom-plugins@latest
import { filter } from '@zumer/snapdom-plugins/filter';
import { timestampOverlay } from '@zumer/snapdom-plugins/timestamp-overlay';
PDF, Vector and Stream are separate packages. See community plugins for packages by other authors.
Redact fields, blocks and attributes
redactInputs() masks field values, hides or removes private blocks and strips named attributes from images, HTML and structured exports. The rules for fields, blocks and attributes, and their limits, are documented on the redact-inputs page.
Build a plugin
This plugin changes the heading in the captured copy. The live heading stays the same:
import { snapdom } from '@zumer/snapdom';
const card = document.createElement('article');
card.innerHTML = '<h2>Original title</h2>';
document.body.appendChild(card);
const titlePlugin = {
name: 'capture-title',
afterClone({ clone }) {
clone.querySelector('h2').textContent = 'Shared copy';
}
};
const result = await snapdom(card, { plugins: [titlePlugin] });
document.body.appendChild(await result.toPng());
For a packaged plugin, start from the project template:
npx degit zumerlab/snapdom/packages/plugin-template my-plugin
Read the plugin specification for hook contracts and the contribution guide for packaging and tests.
Get listed: once your plugin is published, submit a PR adding it to community-plugins.md.
Registering plugins
Global registration (applies to all captures):
import { snapdom } from '@zumer/snapdom';
// Pass plugin objects, calling factories with their options.
snapdom.plugins(
myPluginInstance,
myPluginFactory({ optionA: true }),
anotherFactory({ level: 2 })
);
Per-capture registration (that call only):
const out = await snapdom(element, {
plugins: [
[overlayFilterPlugin, { color: 'rgba(0,0,0,0.25)' }],
[myFullPlugin, { providePdf: true }]
]
});
- Execution order = registration order.
- Per-capture plugins run before global ones.
- Duplicates are skipped by
name; a per-capture plugin with the samenameoverrides its global version.
Lifecycle hooks
Hooks run in capture order (see the capture flow):
| Hook | Stage | Purpose |
|---|---|---|
| beforeSnap | Start | Adjust options before any work. |
| beforeClone | Pre-clone | Before DOM clone (modify live DOM carefully). |
| resolveNode | Per node | Replace or skip a node after the compiled exclusion policy. |
| afterClone | Post-clone | Modify cloned tree safely (e.g. inject overlay). |
| beforeRender | Pre-render | Right before the selected render engine runs. |
| afterRender | Post-render | Inspect context.dataURL / context.meta, and svgString on the SVG path. |
| defineExports | Result setup | After capture, add custom exporters (e.g. toPdf). |
| beforeExport | Per export | Before each toPng, toSvg, etc. |
| afterExport | Per export | Observe the returned result. |
| afterSnap | Once | After the first successful export; cleanup. |
Order: beforeSnap → beforeClone → resolveNode (per node) → afterClone → beforeRender → afterRender → defineExports → [beforeExport → exporter → afterExport] → afterSnap. The bracketed segment repeats per export; afterSnap fires once after the first successful one. Export-hook return values are ignored. Change an export's options in beforeExport, or use defineExports to produce a custom result.
v2.x.x migration: an afterExport return used to become the next hook's payload (it never replaced the caller's output). V3 ignores those returns and gives every hook the same export payload, so remove return-value chaining. The TypeScript name PluginExportFacade is gone; ctx.exports remains available inside defineExports. Infer its type there or use NonNullable<CaptureContext['exports']> after importing CaptureContext.
Context object
Capture hooks share one context with normalized options and stage results. Export hooks get a view for that export:
- Input & normalized options:
element; theoptionsself-reference;needs;shouldExclude(element); and the public capture options such asscale,dpr,width,height,format,backgroundColor,quality, fonts, exclusion, clipping, selection, reconciliation, invalidation, caching, plugins, and engine.formatis canonical; deprecatedtypestays synchronized with it, and changing either inbeforeSnapis honored. - Intermediate values (depending on stage):
clone,classCSS,styleCache,nodeMap,fontsCSS,baseCSS,svgString,dataURL, and frozenmeta. Large clone-stage fields are released after rendering. - Result setup:
artifacts = { classCSS, fontsCSS, baseCSS, scrollbarCSS }andexports, the hook-free core exporter facade available todefineExports. - During export:
context.export = { type, options, requestedOptions, url, svgString }.typeis the exporter name; frozenrequestedOptionsis what the caller supplied;optionsis the merged bag passed to the exporter.urlis the captured data URL: SVG normally, PNG after a successful native capture.svgString()lazily decodes an SVG capture and throws for a raster capture.
Change capture options in beforeSnap, except plugins, needs, invalidate and cache, which are already resolved. In beforeExport(ctx, payload), mutate payload.options; the context view does not steer that export.
Pipeline depth and memoization
A per-capture plugin may declare needs: "clone" or needs: "render" (the default). SnapDOM runs to the deepest requested stage. A clone-only result can expose plugin outputs such as context or an element map, but reading url or calling an image exporter throws. It does not recapture on demand. Global plugins must use "render".
Clone/render-affecting hooks suspend automatic repeat memoization unless the plugin declares pure: true. Pure beforeRender/afterRender hooks may also use differential recapture, while hooks involved in clone construction still force a conservative full recapture after a change. A capture stopped at needs: "clone" is never memoized because it has no render artifact. Declare purity only for deterministic, idempotent hooks; export-only hooks and defineExports do not need it.
context.shouldExclude(node) covers both exclude and filter, following updates made in beforeSnap. Content selection checks data-capture="exclude", then exclude, then filter; the first omission decides its independent excludeMode or filterMode. resolveNode(node, context) runs after those checks. Return a replacement Node, null to skip, or undefined to continue normal cloning.
Custom exports via plugins
Plugins add exports through defineExports(context). Each key you return (e.g. "pdf") becomes a method on the capture result (toPdf()).
Use several outputs from one capture:
import { snapdom } from '@zumer/snapdom';
import { htmlExport, contextExport } from '@zumer/snapdom-plugins';
const out = await snapdom(element, {
plugins: [htmlExport(), contextExport()]
});
Call the custom export:
const png = await out.toPng();
const html = await out.toHtml();
const context = await out.toContext({ format: 'json' });
Example: overlay filter plugin
This example dims the captured HTML with a translucent overlay. Only the clone changes; the live page stays untouched.
/**
* Overlay filter for captured HTML.
* Inserts a full-size <div> overlay on the cloned root.
*
* @param {{ color?: string; blur?: number }} [options]
* color: overlay color (rgba/hex/hsl). Default: 'rgba(0,0,0,0.25)'
* blur: optional blur in px (default: 0)
*/
export function overlayFilterPlugin(options = {}) {
const color = options.color ?? 'rgba(0,0,0,0.25)';
const blur = Math.max(0, options.blur ?? 0);
return {
name: 'overlay-filter',
/**
* Add a full-coverage overlay to the cloned HTML root.
* @param {any} context
*/
async afterClone(context) {
const root = context.clone;
if (!(root instanceof HTMLElement)) return; // HTML-only
// Ensure containing block so absolute overlay anchors to the root
if (getComputedStyle(context.element).position === 'static') {
root.style.position = 'relative';
}
const overlay = document.createElement('div');
overlay.style.position = 'absolute';
overlay.style.left = '0';
overlay.style.top = '0';
overlay.style.right = '0';
overlay.style.bottom = '0';
overlay.style.background = color;
overlay.style.pointerEvents = 'none';
if (blur) overlay.style.filter = `blur(${blur}px)`;
root.appendChild(overlay);
}
};
}
Usage:
import { snapdom } from '@zumer/snapdom';
// Global registration
snapdom.plugins(overlayFilterPlugin({ color: 'rgba(0,0,0,0.3)', blur: 2 }));
// Per-capture
const out = await snapdom(document.querySelector('#card'), {
plugins: [[overlayFilterPlugin, { color: 'rgba(255,200,0,0.15)' }]]
});
const png = await out.toPng();
document.body.appendChild(png);
The source element supplies the live position value because the clone is detached.
Full plugin template
Use this as a starting point for custom logic or exporters.
export function myPlugin(options = {}) {
return {
/** Unique name used for de-duplication/overrides */
name: 'my-plugin',
/** Optional pipeline depth; global plugins must remain at "render". */
needs: 'render',
/** Set true only for deterministic/idempotent clone or render hooks. */
pure: false,
/** Early adjustments before any clone/style work. */
async beforeSnap(context) {},
/** Before subtree cloning (use sparingly if touching the live DOM). */
async beforeClone(context) {},
/** Per source node, after context.shouldExclude(node) has been applied. */
async resolveNode(node, context) {},
/** After subtree cloning (safe to modify the cloned tree). */
async afterClone(context) {},
/** Right before the selected renderer runs. */
async beforeRender(context) {},
/** After rendering; svgString exists only on the SVG path. */
async afterRender(context) {},
/**
* Define custom exporters during result setup.
* Return a map { [key: string]: (ctx:any, opts:any) => Promise<any> }.
*/
async defineExports(context) { return {}; },
/** Before EACH export call (toPng/toSvg/toBlob/...). */
async beforeExport(context, { format, options }) {},
/**
* After EACH export call.
* Observes { format, options, result }; return values are ignored.
*/
async afterExport(context, { format, options, result }) {},
/** Runs ONCE after the FIRST successful export finishes (cleanup). */
async afterSnap(context) {}
};
}
Before using a plugin in production:
- Keep frozen data on the capture context, not a shared plugin closure.
- Test repeated exports and concurrent captures with the same plugin instance.
- Use the core
exportsfacade fromdefineExportsfor raster work, so sizing, compressed originals and Safari handling stay consistent. - Test in Chromium, Firefox and Safari, including
scale: 2and changes after the first capture.