October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Use Web Workers with Puppeteer

Use Puppeteer’s page events to track dedicated WebWorkers, page.workers() to inspect the current snapshot, and worker.evaluate() to run code in a worker context.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Puppeteer’s Page events to catch dedicated WebWorkers as they start and stop, page.workers() to get the dedicated workers currently associated with a page, and methods such as worker.evaluate() to run code in a worker. These APIs do not make page.workers() a ServiceWorker inventory.

Listen for workers and inspect the current ones

Register lifecycle listeners before navigating if you need to observe workers created during the initial load. The workercreated and workerdestroyed events are emitted on the page; their callbacks receive a worker object. After navigation, call page.workers() for a snapshot of the dedicated WebWorkers associated with that page.

As an Amazon Associate I earn from qualifying purchases.

The following ES-module example uses the documented event names, snapshot method, worker URL, and evaluation API. A particular site may or may not create a worker.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();

try {
  const page = await browser.newPage();

  page.on('workercreated', worker => {
    console.log('Worker created:', worker.url());
  });

  page.on('workerdestroyed', worker => {
    console.log('Worker destroyed:', worker.url());
  });

  await page.goto('https://example.com');

  for (const worker of page.workers()) {
    console.log('Current worker:', worker.url());
    const result = await worker.evaluate(() => ({
      href: self.location.href,
      hasNavigator: typeof navigator !== 'undefined',
    }));
    console.log(result);
  }
} finally {
  await browser.close();
}

For a CommonJS project, replace the import with const puppeteer = require('puppeteer'); and run the code in an async function. Install Puppeteer in the project with npm install puppeteer; this example assumes the installed package and browser setup support the shown APIs.

Choose events or a snapshot

Need Use What it tells you
React as a worker appears or disappears page.on('workercreated', handler) and page.on('workerdestroyed', handler) Lifecycle events for dedicated WebWorkers associated with the page.
Inspect workers associated now page.workers() An array of current dedicated WebWorker objects.

These approaches complement each other: listeners observe future lifecycle changes; the snapshot reports the workers present when called. Puppeteer’s WebWorker API reference documents the events and worker object, while the Page.workers() reference describes the snapshot.

Run code in a worker context

Call worker.evaluate(fn, ...args) to execute a function in that worker. Puppeteer waits for a returned promise to resolve. Pass serializable arguments and prefer simple values—primitives, arrays, and plain objects—for results that need to cross back to Node.js.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
const worker = page.workers()[0];

if (worker) {
  const state = await worker.evaluate(async () => {
    // This function runs in the worker context.
    return {
      url: self.location.href,
      ready: true,
    };
  });
  console.log(state);
}

Use worker.evaluateHandle() instead when you need a live object handle or a value that does not serialize reliably. Handles have a lifecycle; dispose of ones you no longer need. The API warns that protocol serialization can truncate complex values or yield an empty object. See the worker evaluate reference for evaluation behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wait for a worker condition

worker.waitForFunction() waits until a function evaluated in that worker returns a truthy value. The API supports options including polling, timeout, and an abort signal; check the reference matching your installed Puppeteer version for the exact option signatures.

Dedicated WebWorkers are not ServiceWorkers

page.workers() returns dedicated WebWorkers associated with a page; it explicitly excludes ServiceWorkers. Do not describe it as listing every worker type in the browser. The available API references do not establish a complete ServiceWorker workflow here, so consult the target and browser-context APIs for your installed Puppeteer release before building one.

Do not treat document preloads as worker preloads

page.evaluateOnNewDocument() runs in a page document after it is created but before page scripts, including for navigations and child frames. Its documentation does not say that the function runs inside WebWorker contexts, so do not rely on it to initialize workers. See the evaluateOnNewDocument reference.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Troubleshoot missing workers and unexpected results

  • No worker event appeared: Events only help with lifecycle changes observed after the listener is attached. Attach listeners before navigation to catch workers created during initial loading, then call page.workers() to check the current snapshot. The page may simply not create a dedicated worker.
  • The snapshot is empty: Confirm the target page actually starts a dedicated WebWorker and that you are inspecting the expected page. ServiceWorkers are not included in this array.
  • An evaluated result is incomplete or becomes {}: Return simpler serializable data, or use evaluateHandle() if you need a live or complex object.
  • A preload does not run in the worker: evaluateOnNewDocument() is documented for page documents, not worker contexts.
  • Considering direct construction: Do not call or subclass the WebWorker constructor. Puppeteer marks it internal and advises third parties not to do so.
  • An API signature differs: Puppeteer documentation pages may display different version labels. Check the API reference and types for the Puppeteer release installed in your project; the examples here should not be read as a compatibility guarantee for every release.

Or skip the browser setup

If your goal is a screenshot rather than inspecting worker internals, ScreenshotNeo offers a one-request screenshot API:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

See the ScreenshotNeo API documentation for request options. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000.

Sign up free for ScreenshotNeo.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Frequently Asked Questions

Does Puppeteer’s page.workers() include shared or service workers?

It returns dedicated WebWorkers associated with the page and excludes ServiceWorkers. Do not use it as a browser-wide worker inventory.

Can I use page.evaluateOnNewDocument() to inject code into a WebWorker?

The API documents injection into page documents, not worker contexts; it does not establish this as a worker preload hook.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.