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 Dispose of a JavaScript Handle in Puppeteer

Use await handle.dispose() after the last operation that needs a Puppeteer handle. Learn how ElementHandle cleanup works, when contexts dispose of handles automatically, and when a locator or returned value is a better fit.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Call and await the handle’s dispose() method when you are finished with it: await handle.dispose();. This releases the referenced page object for garbage collection. ElementHandle inherits the same method from JSHandle.

Dispose of a handle after its last use

A JSHandle is a retained reference to an object in the page’s JavaScript context. For example, page.evaluateHandle() returns a handle rather than a serialized value. While you need that reference, keep the handle; once you do not, dispose of it:

As an Amazon Associate I earn from qualifying purchases.

const handle = await page.evaluateHandle(() => window);

// Use handle while you need the page object reference.

await handle.dispose();

dispose() returns a Promise<void>, so use await when you want cleanup to complete before the surrounding code continues. Disposal releases the referenced object for garbage collection; it does not promise that memory will be reclaimed immediately.

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

Dispose of an ElementHandle the same way

An ElementHandle is a handle to a DOM element and inherits JSHandle’s disposal behavior. If you use a selector API that returns an element handle, dispose of it after its final operation. A finally block ensures cleanup is attempted even if the operation throws:

const element = await page.waitForSelector('div.example');

try {
  if (element) {
    await element.click();
  }
} finally {
  await element?.dispose();
}

The null check matters: a selector result can be null when no element matches, and there is no handle to dispose in that case. The optional chain in the cleanup also makes the disposal safe for that result.

Example: read a value and then release the handle

Use a handle when the next operation needs access to the actual page object. For example, pass a body handle into page.evaluate(), then dispose of it after extracting the HTML:

const bodyHandle = await page.$('body');

if (!bodyHandle) {
  throw new Error('The page body was not found');
}

try {
  const html = await page.evaluate(body => body.innerHTML, bodyHandle);
  console.log(html);
} finally {
  await bodyHandle.dispose();
}

This example uses the handle only for the evaluation. If an API that returns the value you need directly fits the task, that can avoid keeping a live page-object reference.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

When cleanup happens automatically

Puppeteer automatically disposes associated JavaScript handles when their frame navigates away or their parent execution context is destroyed. That lifecycle cleanup is useful, but it is not a reason to retain handles unnecessarily while a context remains active. For a live handle you are done using, explicitly call await handle.dispose().

Disposal is documented as releasing the reference for garbage collection—not as immediately freeing a measurable amount of memory. Do not rely on repeated calls being harmless; dispose of a handle once, after its final use.

Use a locator or a returned value when a handle is unnecessary

For ordinary element selection and interaction, Puppeteer’s current guidance recommends locators. A locator is often a better fit when the task is simply to find an element and click or fill it, rather than retain a reference to a particular page object. For extraction, prefer an API that returns a serializable value when you do not need the live object itself.

Choose a retained handle when later code genuinely needs that page object reference, such as when passing an element into an evaluation. Choose a locator for normal selection and interaction, or a returned value when you only need data. A handle returned by a lower-level API such as waitForSelector() remains your responsibility to dispose of after its last use.

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

Troubleshooting handle cleanup

  • “Cannot read properties of null” during cleanup: the selector did not produce an element. Check the result before using it and use optional cleanup such as await element?.dispose().
  • The page object is still needed after disposal: move disposal until after the final operation. Once you dispose of a handle, do not plan to use it as a live reference.
  • A handle becomes unavailable after navigation: its frame or parent execution context may have been destroyed; Puppeteer automatically disposes handles associated with that context. Obtain a fresh handle in the current page context if the operation still needs one.
  • You expected jsonValue() to clean up the handle: serialization and disposal are different operations. jsonValue() returns serializable portions as a vanilla value; it is not documented as disposing of the originating handle. It can throw for circular structures and does not call toJSON.
  • You expected disposal to free memory immediately: disposal releases the reference for garbage collection, but Puppeteer does not promise immediate reclamation or a specific amount of memory freed.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your task is to capture a website screenshot rather than manage a Puppeteer handle, ScreenshotNeo provides a screenshot API and MCP server. It does not replace JSHandle.dispose(); it avoids setting up a browser for screenshot capture.

Best Value
The SQL Programming Language: .
  • Used Book in Good Condition

One GET request returns an image or PDF. This cURL example saves a WebP screenshot:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for options. Cookie banners, newsletter popups and chat widgets are removed before capture; bot checks, blank pages and failed loads are never billed. An MCP server lets AI agents use screenshot tools. The free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000 screenshots. Sign up for free.

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

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.