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 desk3 min

How to Add a Custom Query Handler in Puppeteer

Learn how to register a named Puppeteer custom query handler, use it with locators, compose its selector, and troubleshoot legacy syntax and framework-coupled logic.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Register a handler with Puppeteer.registerCustomQueryHandler(name, handler), then use its name in a custom pseudo-element selector such as ::-p-reactComponent(MyComponent). Implement queryOne for the first match and queryAll for all matches; for new code, use the pseudo-element syntax because it supports selector composition and is the current guide’s pattern.

Register the handler

The registration API takes a name and an object containing query methods. The name may contain only upper- and lower-case Latin letters, so use a camel-case name such as reactComponent, not a hyphenated name.

As an Amazon Associate I earn from qualifying purchases.

import { Puppeteer } from 'puppeteer';

Puppeteer.registerCustomQueryHandler('reactComponent', {
  queryOne: (elementOrDocument, selector) => {
    return elementOrDocument.querySelector(`[id="${CSS.escape(selector)}"]`);
  },
  queryAll: (elementOrDocument, selector) => {
    return elementOrDocument.querySelectorAll(`[id="${CSS.escape(selector)}"]`);
  },
});

This example treats the selector argument as an ID value, escaping it before interpolating it into a CSS attribute selector. The callback receives a DOM element or document in the page context; it should use APIs available there, rather than relying on variables from your Node.js scope. A handler may implement only the query method it needs.

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

Use the handler with a locator

After registering the handler, use its name in the ::-p-name(argument) form. Puppeteer recommends locators for selecting elements and interacting with them.

const element = await page.locator('::-p-reactComponent(MyComponent)').click();

The sample looks for an element whose id equals MyComponent, then clicks it. Adapt the handler’s query logic and the argument to match the elements your page exposes.

Choose the current selector syntax

Form Example Use and limitation
Custom pseudo-element ::-p-reactComponent(MyComponent) Preferred for new code; the current guide demonstrates it and it can be composed with other selectors.
Legacy prefix text/My text Retained in the API documentation as a legacy form. It runs one non-CSS selector at a time and cannot combine multiple selectors.

For example, a custom selector can be composed with a regular CSS selector: .side-bar ::-p-reactComponent(MyComponent). This lets the custom handler participate in a larger selector rather than being limited to a single prefixed query.

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

Keep handler logic maintainable

  • Prefer stable, user-facing DOM properties where possible. A handler that depends on framework implementation details may stop working when those internals change.
  • The official Vue example demonstrates traversing internal vnode fields, but that is a fragile integration unless you intentionally pin and maintain the framework representation it relies on.
  • Use queryOne when the handler needs to return its first match and queryAll when it needs to return all matches. Keep their behavior aligned with the selector argument’s meaning.

Version and migration notes

Puppeteer’s API reference identifies version 25.3.0, while its current page-interactions guide identifies version 25.12.0. Check the documentation for the version installed in your project before depending on version-specific details: API reference and page interactions guide.

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.

The Puppeteer 23.0.0 changelog, dated 2024-08-07, records removal of deprecated functions for CustomQueryHandler. If older code uses those functions, consult the changelog and migrate to the supported registration and query-method pattern.

Troubleshoot common problems

  • Registration rejects the name: use only upper- and lower-case Latin letters; remove hyphens, underscores, digits, and other punctuation.
  • The pseudo-element does not resolve: confirm the registered name and selector name match, including capitalization, and that registration occurs before the locator is used.
  • The handler cannot access a Node variable: its callback runs in the page context. Pass needed data through the selector argument or otherwise make it available through page-context logic.
  • A legacy selector cannot be combined: replace the name/selector prefix with ::-p-name(argument) when composition is needed.
  • A framework-specific query breaks after an upgrade: the handler may rely on unstable internals. Prefer stable DOM attributes or update and validate the integration against the framework version you use.
  • Old handler code fails after a Puppeteer upgrade: check whether it calls deprecated functions removed in Puppeteer 23.0.0, then compare it with the API reference for your installed version.
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 goal is simply to capture a webpage rather than interact with it through Puppeteer, ScreenshotNeo is a website screenshot API and MCP server. One GET request returns an image or PDF; its clean-shot steps accept consent banners and remove supported cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits cost nothing, and response headers report the page verdict and whether the request was billed. Its MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf.

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 request options. The Free plan includes 1,000 screenshots a month without a card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.

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

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

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.