window.print With beforeprint State Swap

Open the print dialog with window.print() and use beforeprint/afterprint listeners to swap chart markup for print-friendly tables and restore it after.

TypescriptData Integrity

Code

typescriptsnippet
20 lines
// window.print() opens the print dialog; beforeprint/afterprint bracket it so
// screen-only state can be swapped for a print-friendly one and restored.
const chart = document.querySelector<HTMLElement>('#chart-summary');
const table = document.querySelector<HTMLElement>('#chart-table');

window.addEventListener('beforeprint', () => {
  if (!chart || !table) return;
  chart.hidden = true;
  table.hidden = false; // paper needs the numbers, not the visualization
});

window.addEventListener('afterprint', () => {
  if (!chart || !table) return;
  chart.hidden = false;
  table.hidden = true;
});

document.querySelector<HTMLButtonElement>('#print-btn')?.addEventListener('click', () => {
  window.print();
});

Inside the code

The file’s state is a handful of top-level bindings: chart, table.

What to watch for

  • Dependency-free as written — nothing in a registry, nothing in a lockfile.
  • A browser is the runtime here: document, window are not available in Node.
  • The guard !chart || !table cuts the flow short with an early return when its condition holds.

Statements that matter

document.querySelector<HTMLButtonElement>('#print-btn')?.addEventListener('click', () => {
  window.print();
});
window.addEventListener('beforeprint', () => {
  if (!chart || !table) return;
  chart.hidden = true;
  table.hidden = false; // paper needs the numbers, not the visualization
});
window.addEventListener('afterprint', () => {
  if (!chart || !table) return;
  chart.hidden = false;
  table.hidden = true;
});

Interactive Tools for This Topic

FAQ

Does window.print With beforeprint State Swap run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.