October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Chrome DevTools Protocol

How to Wait for a Custom Element Before Generating a PDF in Go

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

Use customElements.whenDefined() to wait until the browser knows the custom element, then wait for the page’s own signal that its data and rendering are ready before calling chromedp’s PDF command. A defined element is not necessarily finished rendering, and neither a selector wait nor network idleness proves that it is.

What “ready” means for a custom element

There are two separate milestones: the browser registers the element’s constructor, and the component finishes the work needed for the printed document. The HTML Standard defines customElements.whenDefined(name) as a promise fulfilled with the constructor when that valid custom element becomes defined; if it is already defined, the promise fulfills immediately. See the WHATWG HTML Standard.

That promise does not wait for a component’s network requests, data fetching, nested components, chart drawing, image loading, or layout to settle. There is no universal browser property named ready that covers these tasks. Use a readiness contract documented by the page or component, or have the page expose one explicitly.

Wait for definition and page readiness with chromedp

The example below navigates to a page, waits for the report-card definition, checks that an instance exists, awaits a page-owned readiness promise, waits for document fonts, and then writes PDF bytes to a file. The readiness property is deliberately application-specific: window.__PDF_READY__ is an example, not a built-in browser 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.
#1 Best Overall
Epson EcoTank ET-2800 Wireless Color All-in-One Supertank Printer - Black
  • INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
  • COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
  • ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
  • HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs
package main

import (
	"context"
	"os"
	"time"

	"github.com/chromedp/cdproto/page"
	"github.com/chromedp/chromedp"
)

func capturePDF(parent context.Context, targetURL, outputPath string) error {
	// Bound the navigation, readiness wait, and PDF generation together.
	ctx, cancel := context.WithTimeout(parent, 60*time.Second)
	defer cancel()

	// NewContext controls a compatible Chrome/Chromium instance. If your
	// application uses a remote browser, create the chromedp context for it.
	ctx, cancelBrowser := chromedp.NewContext(ctx)
	defer cancelBrowser()

	var pdf []byte
	err := chromedp.Run(ctx,
		chromedp.Navigate(targetURL),
		chromedp.Evaluate(`(async () => {
			await customElements.whenDefined('report-card');

			const el = document.querySelector('report-card');
			if (!el) throw new Error('report-card was not found');
			if (!window.__PDF_READY__) {
				throw new Error('page must expose its PDF readiness promise');
			}

			await window.__PDF_READY__;
			await document.fonts.ready;
			return true;
		})()`, nil),
		chromedp.ActionFunc(func(ctx context.Context) error {
			var err error
			pdf, _, err = page.PrintToPDF().WithPrintBackground(true).Do(ctx)
			return err
		}),
	)
	if err != nil {
		return err
	}
	return os.WriteFile(outputPath, pdf, 0o644)
}

This is an implementation pattern, not a tested program for every chromedp release or target page. Pin compatible versions of chromedp and cdproto, and verify their APIs. The code uses page.PrintToPDF and the WithPrintBackground option; the generated Page API returns PDF bytes, which the example saves. Consult the cdproto Page API and the chromedp project documentation for version-specific details.

Expose a readiness contract on the page

The page should resolve its PDF readiness promise only after the content required in the printed output is complete. For example, application code might assign a promise that encompasses data loading and component rendering:

window.__PDF_READY__ = (async () => {
  await loadReportData();
  await renderReportCards();
  await waitForRequiredImages();
})();

The function names above are illustrative; use the target application’s real operations. Reject the promise when an unrecoverable failure means the document cannot be prepared. In production, make failures observable in Go and return them rather than printing a partial document.

If the component already documents a readiness promise or state, wait for that contract instead of adding a second one. If several tag definitions matter, await them together:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await Promise.all([
  customElements.whenDefined('report-card'),
  customElements.whenDefined('report-chart'),
]);

Then wait for whatever application state establishes that those components have rendered the required content. If the relevant element is inside another frame, run the wait in that frame’s execution context. A top-level registry lookup or selector is not automatically a complete check for every frame and shadow-tree arrangement; inspect how the page registers and renders its components.

Choose the right wait instead of guessing

Use whenDefined for late registration

When a script registers the custom element after navigation, whenDefined prevents the capture from racing ahead of registration. It resolves immediately if registration already happened. It does not establish that an instance exists, so query for the element if its presence matters, and fail clearly if it is missing.

Rank #2
Sale
Epson EcoTank Photo ET-8550 Wireless Wide-Format All-in-One Tank Printer
  • CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
  • INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
  • PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
  • ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴

Use application state for completed rendering

A selector or state wait is useful only when it represents the final content contract. Seeing report-card in the DOM, or seeing a “loading” indicator disappear, may still be too early if data, nested components, images, or charts are unfinished. Make the readiness signal correspond to what must actually appear in the PDF.

Do not treat network idle as component readiness

Network idle describes network activity, not whether the application has finished rendering. A page can become quiet while rendering continues, or keep connections open after its printable content is ready. Playwright’s documentation explicitly discourages network-idle as a testing readiness strategy and recommends waiting for the required state instead: Playwright load-state guidance.

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

Avoid fixed sleeps

A fixed delay is a timing guess that can be wasteful on a fast run and too short on a slow one. Give the whole operation a finite Go context deadline and wait for an explicit condition. If the condition does not resolve before the deadline, return the error and investigate the page or timeout budget. The chromedp project documents page-state waits and JavaScript evaluation; use the specific wait supported by your pinned version rather than relying on an arbitrary sleep.

Print options and browser requirements

Chromedp drives Chrome or Chromium through the Chrome DevTools Protocol; it is not itself a browser and does not decide when an application component is ready. A compatible browser runtime must be available locally or reachable through the configured browser connection, and the Go context must remain alive through navigation, waiting, and printing.

page.PrintToPDF().Do(ctx) returns PDF bytes and an error. The generated Page API includes print options such as background printing, page dimensions, margins, landscape orientation, and page ranges; check the version you have installed for exact option names and semantics. WithPrintBackground(true) is appropriate when CSS backgrounds are part of the intended output, but print CSS and page layout still determine the result.

Do not transfer behavior from one automation library to another. Puppeteer documents that its Page.pdf() uses print media and waits for fonts by default (Puppeteer PDF API); that does not establish custom-element readiness in chromedp or guarantee that the page’s data and rendering work are complete.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
  • SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
  • INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
  • KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
  • PREMIUM SUPPORT - Strong technical expertise to solve issues faster
  • THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.

Or skip the browser setup

If you need a clean screenshot or PDF through an API rather than managing a Chrome runtime, ScreenshotNeo provides a one-request website capture API and an MCP server. It does not replace this Go-specific readiness pattern when you need to await an application-owned signal before PDF generation.

Example cURL request using the documented endpoint and parameters:

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 and response details. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up free for 1,000 screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

The evaluation or PDF call times out

Check whether navigation is waiting on an unexpected page event, whether the page-owned promise is still pending, and whether the Go context deadline is long enough for the target page and browser. Add logging around the application readiness contract or return a descriptive rejection when required data cannot load. Increasing the timeout alone will not fix a promise that never settles.

whenDefined never resolves

Confirm that the exact tag name is valid and that the script responsible for defining it loads successfully in the frame where you are evaluating. If the name is already registered, the promise resolves immediately; a hang usually points to a missing or delayed definition, a stalled page, or a wait running in the wrong frame.

The PDF is missing content despite successful waits

Verify that the readiness promise covers the specific content in question. It may need to await data, nested component rendering, chart completion, required images, or other page work. document.fonts.ready addresses document font loading; it does not wait for those other operations. Also check print-specific CSS and whether backgrounds should be enabled.

Rank #4
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
  • No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
  • Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
  • Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
  • The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art

The element exists but its contents are incomplete

Element presence confirms only that a matching node exists. Await the component’s documented ready promise or a page-owned signal that resolves after its printable content has rendered. If the content is in a shadow root, query and assess the relevant state according to that component’s implementation.

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.

The Go code does not compile against the installed packages

Align chromedp and cdproto versions and inspect the documentation for those exact versions. Generated CDP APIs and options can differ across releases. Also confirm imports, context setup, and the return signature of the PDF command in the version you use.

The browser cannot be started or reached

Install or configure a compatible Chrome/Chromium runtime, or point chromedp at the browser connection your deployment provides. Keep the browser and Go contexts alive until the complete operation returns, and ensure cleanup occurs after capture rather than before the PDF action.

Frequently Asked Questions

Can I use this method when the custom element is already defined?

Yes. The standard promise fulfills immediately when that valid custom element is already defined.

Does awaiting document.fonts.ready mean every image is ready?

No. It addresses document font loading only; include image completion in the page’s readiness contract if images are required for the PDF.

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

Quick Recap

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.

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.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.