Most Electron documentation treats a desktop app as something the user sees: a window appears, a renderer paints, the user interacts. But Electron's runtime is also a complete Chromium plus Node.js environment, and that combination is useful even when no window ever appears on screen. You can drive a hidden renderer to scrape pages, export screenshots and PDFs, run batch jobs, smoke-test a UI in CI, or process local documents behind a background task.
This guide covers the real, production-grade patterns for running Electron windowless: the three ways to stay off-screen, a complete working job, capture and export mechanics, lifecycle cleanup, and the pitfalls that hide headless runs until a CI pipeline hangs at 3 a.m.
Table of Contents
- What "headless" means in Electron
- Three ways to run windowless
- Worked example: load, extract, screenshot, PDF
- Common windowless jobs
- Capture and export mechanics
- Lifecycle, cleanup, and avoiding hangs
- Pitfalls and gotchas
- Headless Electron vs Playwright/Puppeteer
- Production checklist
What "headless" means in Electron
Unlike a standalone browser, Electron does not ship a separate --headless rendering binary that you invoke like a CLI tool. "Headless" in Electron is a runtime choice: you create your renderer without showing it, and you drive it through the main process and webContents APIs. There are three distinct ways to achieve that, and choosing the right one matters.
| Approach | Window created | On-screen? | Best for |
|---|---|---|---|
Hidden BrowserWindow (show: false) |
Yes, but invisible | No | Loading real pages, DOM extraction, screenshots, PDF export, automation |
Offscreen webPreferences (offscreen: true) |
Window exists, frames are pushed through a paint event |
No | Server/no-display environments, frame-by-frame capture, resource-constrained hosts |
| App with no window at all | None | No | Pure Node background jobs that only touch the file system or network |
The hidden-window route is by far the most common: you get a full Chromium renderer, normal navigation history, cookies, and the same web APIs your app already uses, just without a visible frame. Offscreen rendering exists for hosts that have no display server and need frames delivered programmatically; a no-window app is for jobs that do not actually render web content.
Three ways to run windowless
1. Hidden BrowserWindow
Create the window with show: false. It still loads pages, runs JavaScript, and renders content; it simply never becomes visible.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
show: false,
width: 1280,
height: 800,
webPreferences: {
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
},
})
This is the default choice whenever you need to inspect a DOM, take a capture, or render a PDF.
2. Offscreen rendering
When the host has no display and you want frames delivered as buffers, enable offscreen rendering:
const win = new BrowserWindow({
show: false,
webPreferences: { offscreen: true },
})
win.webContents.on('paint', (_event, dirty, image) => {
// image is a NativeImage; read dirty rect for partial updates
const png = image.toPNG()
})
Offscreen rendering trades a composited on-screen window for a stream of frames. Use it when you are rendering on a server, processing frames yourself, or avoiding any dependency on a graphical session.
3. No window at all
If your job never renders web content, do not create a window. A plain main-process script with Node modules, net, fs, and child processes is enough:
const { app } = require('electron')
app.whenReady().then(async () => {
// pure Node work: read files, call APIs, write outputs
app.quit()
})
Creating an invisible renderer you never use only adds memory and a renderer process to kill later.
Worked example: load, extract, screenshot, PDF
The following main-process script is a complete, runnable windowless job. It opens a hidden window on a throwaway session, waits for the page to settle, extracts structured data, captures a PNG, exports a PDF, and cleans up explicitly.
const { app, BrowserWindow, session } = require('electron')
const fs = require('fs/promises')
const path = require('path')
function waitForSettle(win, timeoutMs = 15000) {
const wc = win.webContents
return Promise.race([
new Promise((resolve) => wc.once('did-stop-loading', resolve)),
new Promise((resolve) => setTimeout(resolve, timeoutMs)),
])
}
async function runJob(targetUrl, outDir) {
// Throwaway partition: cookies and storage do not leak between jobs.
const sess = session.fromPartition('temp-headless', { cache: false })
const win = new BrowserWindow({
show: false,
width: 1280,
height: 800,
webPreferences: {
session: sess,
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
},
})
await win.loadURL(targetUrl)
await waitForSettle(win)
// Read the DOM from the main process. The expression runs in the page context.
const data = await win.webContents.executeJavaScript(`
({
title: document.title,
heading: document.querySelector('h1')?.textContent ?? null,
links: [...document.querySelectorAll('a')].slice(0, 20).map(a => a.href),
})
`)
const shot = await win.webContents.capturePage()
await fs.writeFile(path.join(outDir, 'shot.png'), shot.toPNG())
const pdf = await win.webContents.printToPDF({ printBackground: true })
await fs.writeFile(path.join(outDir, 'page.pdf'), pdf)
win.destroy()
return data
}
app.whenReady().then(async () => {
try {
const data = await runJob(
'https://example.com',
path.join(__dirname, 'out'),
)
console.log(JSON.stringify(data, null, 2))
} catch (err) {
console.error('job failed:', err)
} finally {
app.quit()
}
})
// We manage quit explicitly; do not let macOS auto-close on the last hidden window.
app.on('window-all-closed', () => {})
A few details are doing real work here:
- The
temp-headlesspartition is ephemeral, so one job's cookies do not seed the next. -
waitForSettleracesdid-stop-loadingagainst a hard timeout, so a slow or hanging network request cannot stall the job forever. -
executeJavaScriptruns in the page's own context; keepnodeIntegration: falseandcontextIsolation: trueeven for automated jobs. -
win.destroy()releases the renderer beforeapp.quit().
Common windowless jobs
The hidden-window pattern adapts to several recurring automation tasks:
-
Scraping and data extraction. Load a page, read the DOM through
executeJavaScript, return plain JSON. For SPAs, poll for a target selector instead of assumingdid-finish-loadmeans content is ready. - Screenshot export. Capture marketing pages, dashboard states, or rendered reports on a schedule, then store or upload the PNG.
-
PDF generation. Render an HTML report or invoice template and
printToPDFit without opening a visible preview window. - Batch document processing. Open multiple hidden windows sequentially (or a small controlled pool), each handling one document, then close it before starting the next.
- UI smoke tests in CI. Launch the app headless, navigate a critical flow, assert on DOM state or a capture, and exit with a real success/failure code.
- Background rendering. Produce images or previews on a server without a desktop session, using offscreen frames.
Capture and export mechanics
Screenshots: capturePage
webContents.capturePage() resolves to a NativeImage. By default it captures the current viewport, not the full scrollable page.
const image = await win.webContents.capturePage()
await fs.writeFile('viewport.png', image.toPNG())
If you need a full-page capture, resize the window to the full content height first, wait for relayout, then capture. Read the scroll height from the page and pass it back:
const { height } = await win.webContents.executeJavaScript(
`({ height: document.documentElement.scrollHeight })`,
)
win.setSize(1280, Math.min(height, 4000))
await new Promise((r) => win.webContents.once('resize', r))
const full = await win.webContents.capturePage()
Set devicePixelRatio on the window when you need a higher-resolution image, and capture only after the first paint; an early capture returns a blank frame.
PDF: printToPDF
printToPDF returns a PDF Buffer. Enable printBackground to keep colors and backgrounds; control margins and page size through the options object.
const pdf = await win.webContents.printToPDF({
printBackground: true,
margins: { top: 0.4, bottom: 0.4, left: 0.4, right: 0.4 },
pageSize: 'A4',
})
await fs.writeFile('report.pdf', pdf)
Printing does not require a visible window, but it does require the renderer to have laid out the page, so wait for settle before exporting.
Waiting for real readiness
did-finish-load fires when the main document loads; it does not wait for images, fonts, XHR data, or SPA hydration. For content-dependent captures and exports, combine a load event with a readiness poll:
async function waitForSelector(win, selector, timeoutMs = 15000) {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
const found = await win.webContents.executeJavaScript(
`!!document.querySelector(${JSON.stringify(selector)})`,
)
if (found) return
await new Promise((r) => setTimeout(r, 200))
}
throw new Error(`selector not found: ${selector}`)
}
Lifecycle, cleanup, and avoiding hangs
The most common headless failure is not a crash — it is a process that never exits. CI jobs hang, batch runners pile up renderer processes, and memory climbs until the host is recycled.
-
Quit explicitly. Call
app.quit()in afinallyblock after the job completes or fails. Do not rely on the app exiting for you. -
Destroy the window.
win.destroy()frees the renderer process and its GPU context; leaving an invisible window around keeps that resident. -
Override
window-all-closed. On macOS, the app keeps running by default when all windows close. For a CLI-style job, either no-op the handler and quit yourself, or quit explicitly once your work is done. -
Reuse sessions deliberately. A persistent partition (
persist:name) keeps cookies and cache across runs; a temp partition does not. Pick one per job and do not mix them. - Bound every wait. Race navigation, selectors, and captures against a timeout so a stalled page cannot block the job indefinitely.
- Limit concurrency. Opening many hidden renderers at once multiplies renderer and GPU memory. Process documents sequentially or keep a small worker pool with a hard cap.
Pitfalls and gotchas
| Symptom | Likely cause | Fix |
|---|---|---|
| Job never exits in CI | Window not destroyed, app.quit() missing, macOS auto-keep-alive |
Destroy window; quit in finally; override window-all-closed
|
| Blank or white PNG | Capture taken before first paint / settle | Wait for dom-ready + did-stop-loading or a selector before capturePage
|
| Layout looks wrong on Linux CI | Missing fonts, default software rendering | Install system fonts; set explicit window size; pass disable-gpu in containers |
| Capture is only the viewport |
capturePage defaults to viewport |
Resize to full content height, or slice the page manually |
| Spots stale cookies between jobs | Reused persistent partition | Use an ephemeral temp- partition for isolated jobs |
| SPA content missing in extraction | Read DOM before hydration finishes | Poll for a target selector; do not trust did-finish-load
|
| PDF drops colors/backgrounds |
printBackground off |
Set printBackground: true
|
| Process leaks memory over a batch | Hidden renderers reused without close | Destroy each window after its document; cap concurrency |
| Container fails to start sandbox | Restricted container seccomp profile | Pass --no-sandbox only in trusted CI/container hosts; never loosen this on a user machine |
To add low-level Chromium switches for a headless host, append them before app.ready:
app.commandLine.appendSwitch('disable-gpu')
// Only in trusted containers:
// app.commandLine.appendSwitch('no-sandbox')
Headless Electron vs Playwright/Puppeteer
Electron is not the only way to drive a hidden Chromium, and it is not always the right one.
| Dimension | Headless Electron | Playwright / Puppeteer |
|---|---|---|
| Reuse existing desktop code | Strong: same main/renderer architecture, native modules, local FS | Weak: separate browser automation harness |
| Node ecosystem inside the job | Native: full Node runtime in main process | Limited to the automation bridge |
| Parallel browser instances | Manual: you manage a window pool | Built-in context/worker model, mature |
| Setup weight | Full Electron app packaging | Lightweight downloaded browser binaries |
| Best fit | Reusing an Electron codebase, local files, native addons, signed desktop distribution | Pure web scraping, broad cross-browser testing, high-volume automation |
Choose headless Electron when the value is in your existing desktop application code: bundled native modules, local file access, Electron APIs, or a signed app you already distribute. Reach for Playwright or Puppeteer when the job is purely web-facing and you want the mature parallel-browser tooling ecosystem.
Production checklist
Before running a windowless Electron job unattended, confirm:
- [ ] Window is created
show: false, or offscreen/no-window as appropriate. - [ ] Every wait (load, selector, capture) has a hard timeout.
- [ ] Renderer preferences stay locked down:
contextIsolation: true,sandbox: true,nodeIntegration: false. - [ ] Session partition matches the job's isolation needs; temp partitions for one-off jobs.
- [ ] Window is destroyed and
app.quit()runs in afinallyblock. - [ ]
window-all-closedbehavior is intentional for the platform. - [ ] Screenshots/PDFs are captured after layout and fonts settle.
- [ ] Linux/container hosts have fonts, GPU fallback switches, and a reviewed sandbox posture.
- [ ] Concurrency is capped; failed jobs still release resources and exit non-zero.
Conclusion
Electron's power is usually framed around visible desktop apps, but the same runtime makes a capable headless automation host: a hidden renderer, Node on the main process, structured DOM reads, screenshots, PDFs, and explicit lifecycle control. The patterns are simple once you treat a windowless job like any other service — isolate its session, bound its waits, release its resources, and exit with a real status code. Done that way, Electron runs reliably in CI, on servers, and in the background, without ever showing a window to the user.
Top comments (0)