Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Run a custom function in a headless browser with Playwright or Puppeteer by passing a callback to page.evaluate(). The callback executes inside the web page, where window and document exist; your Node.js automation code runs in a separate context. Pass every input explicitly, return a serializable value, and await the result. Use an initialization script when code must run before the page’s scripts, or an exposed function when page code must call back into Node.js.
What “custom function” means in a headless browser
Headless automation has two JavaScript environments:
- Automation context: your Playwright or Puppeteer script, running in Node.js.
- Page context: JavaScript inside the loaded website, with browser globals such as
window,document, storage, and DOM APIs.
page.evaluate() serializes a function, sends it to the page context, executes it there, and transfers the returned value back. A local variable in your Node.js file is not automatically visible to the callback. Arguments and the return value must be transferable between contexts.
Both Playwright and Puppeteer wait for a Promise returned by the callback. If the result cannot be serialized, the caller generally receives undefined (apart from values specially supported by the library), so return plain objects, arrays, strings, numbers, booleans, or null.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problems#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Run a function with Playwright
Minimal example: read the title
import { chromium } from 'playwright';
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://example.com');
const pageTitle = await page.evaluate(() => document.title);
console.log(pageTitle);
await browser.close();
The arrow function is evaluated in the page, not in the Node.js process. Consequently, document.title is valid inside the callback.
Pass arguments explicitly
const productCount = await page.evaluate((selector) => {
return document.querySelectorAll(selector).length;
}, '.product-card');
console.log(`Found ${productCount} products`);
Playwright supplies the second argument to the callback’s selector parameter. This pattern avoids relying on variables that exist only in the test script.
Return structured data
const products = await page.evaluate(() => {
return [...document.querySelectorAll('.product-card')].map(card => ({
name: card.querySelector('.name')?.textContent?.trim() ?? null,
price: card.querySelector('.price')?.textContent?.trim() ?? null,
href: card.querySelector('a')?.href ?? null
}));
});
console.log(products);
Convert DOM nodes to plain data before returning them. Returning an Element, a function, or an object containing circular references is not a reliable cross-context result.
Use asynchronous page code
const result = await page.evaluate(async (endpoint) => {
const response = await fetch(endpoint);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
return { count: data.items?.length ?? 0 };
}, 'https://api.example.com/items');
console.log(result);
Because the callback is async, Playwright waits for its returned Promise. Errors thrown in the page are propagated to the Node.js call, so wrap the evaluation in try/catch when you need custom reporting.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Run a function with Puppeteer
Basic evaluation
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'networkidle2' });
const title = await page.evaluate(() => document.title);
console.log(title);
await browser.close();
Pass selectors and return values
const count = await page.evaluate((selector) => {
return document.querySelectorAll(selector).length;
}, '.product-card');
const links = await page.evaluate(() => {
return [...document.querySelectorAll('a[href]')].map(a => ({
text: a.textContent.trim(),
href: a.href
}));
});
Puppeteer serializes the callback before sending it to the page. It therefore cannot use lexical variables or helper functions defined only in the caller. Pass values as parameters and define any required helper logic inside the callback.
Await a Promise in Puppeteer
const status = await page.evaluate(async (url) => {
const response = await fetch(url, { method: 'HEAD' });
return response.status;
}, 'https://example.com');
console.log(status);
The Promise returned by the callback is awaited before page.evaluate() resolves.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Playwright and Puppeteer: choosing the right API
| Question | Playwright | Puppeteer |
|---|---|---|
| How do I execute page-context code? | page.evaluate(callback, ...args) |
page.evaluate(callback, ...args) |
| Can an async callback be awaited? | Yes; returned Promises are awaited. | Yes; returned Promises are awaited. |
| How are inputs transferred? | Pass them as evaluation arguments. | Pass them as evaluation arguments. |
| What should be returned? | Serializable data; unsupported values may resolve to undefined. |
Serializable data; unsupported values may resolve to undefined. |
| Which is faster or more compatible? | The reviewed documentation does not establish a general performance or compatibility ranking. Use the library already used by your project, its supported runtime, and its surrounding APIs. | |
The core evaluation model is equivalent. Your existing stack, language/runtime requirements, and control flow should determine the choice rather than an unsupported speed claim.
Move data safely across the boundary
Inputs
Pass primitives, arrays, and plain objects as arguments. Keep the boundary explicit:
Free tools Windows power users keep installed
One-click scans. No signup required.
const config = { currency: 'USD', includeOutOfStock: false };
const rows = await page.evaluate((cfg) => {
return [...document.querySelectorAll('[data-price]')]
.map(el => ({
raw: el.getAttribute('data-price'),
currency: cfg.currency
}));
}, config);
Do not pass secrets into page code unless the page genuinely needs them: an evaluated callback can expose those values to the site’s JavaScript and browser tooling.
Results
Extract the fields you need rather than returning DOM objects:
const summary = await page.evaluate(() => ({
url: location.href,
title: document.title,
bodyTextLength: document.body?.innerText.length ?? 0
}));
Navigation and lifetime
Evaluation callbacks are tied to the current document. Functions supplied through evaluation are cleared on top-level navigation. If a callback is needed after every navigation, register the appropriate page hook again or use an initialization script.
When evaluate() is not the right tool
Run before the page’s own scripts
page.evaluate() runs after a document exists and is therefore too late for some instrumentation, shims, or configuration. Playwright’s page.addInitScript() injects code after the document is created but before that document’s own scripts run:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
await page.addInitScript(() => {
Object.defineProperty(navigator, 'language', {
get: () => 'en-US'
});
});
await page.goto('https://example.com');
Use this timing deliberately; changing browser-visible APIs can affect site behavior and test validity.
Let page code call Node.js
If the website must invoke a callback implemented in your automation process, expose a function instead of polling with evaluate(). Playwright’s page.exposeFunction() adds a callable function to the page and survives navigation:
await page.exposeFunction('reportMetric', async (name, value) => {
console.log({ name, value, receivedAt: Date.now() });
});
await page.evaluate(() => {
window.reportMetric('checkout_loaded', performance.now());
});
This is the opposite direction from ordinary evaluation: page JavaScript initiates the call, while the implementation runs in the Playwright environment.
Reliable patterns for production scripts
Wait for the state your function needs
An evaluation callback sees the DOM at the instant it runs. Wait for a selector, a navigation condition, or an application-specific readiness signal before extracting data. A selector wait is usually clearer than a fixed sleep:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchawait page.waitForSelector('.product-card');
const count = await page.evaluate(() =>
document.querySelectorAll('.product-card').length
);
Keep callbacks small
Use the automation API for navigation, waiting, screenshots, and network control; use page evaluation for operations that truly require browser globals or DOM access. Smaller callbacks are easier to serialize, debug, and review.
Handle page errors separately
try {
const value = await page.evaluate(() => {
const node = document.querySelector('[data-total]');
if (!node) throw new Error('total element is missing');
return node.textContent.trim();
});
console.log(value);
} catch (error) {
console.error('Page evaluation failed:', error);
}
Control resource and security boundaries
- Validate URLs and selectors supplied by users before navigating or evaluating them.
- Never interpolate untrusted text into JavaScript source. Pass it as an argument.
- Apply timeouts to navigation and asynchronous work so a page cannot hold a worker forever.
- Close pages and browsers in a
finallyblock in long-running jobs. - Remember that page code runs with the site’s origin permissions; avoid evaluating arbitrary code on sensitive authenticated pages.
Troubleshooting common failures
“Variable is not defined”
Cause: the callback cannot see a Node.js lexical variable. Fix: pass it as an argument:
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
const value = await page.evaluate((input) => input.toUpperCase(), userValue);
The result is undefined
Cause: the callback did not return a value, or the value is not serializable. Fix: use an explicit return and convert DOM objects to plain data.
“document is not defined”
Cause: DOM code was executed in Node.js rather than inside page.evaluate(). Fix: move that expression into the callback.
The selector returns zero elements
Cause: the page has not rendered the target, the selector is wrong, or content is inside a frame or shadow root. Fix: wait for the correct state, verify the selector in browser developer tools, and use the relevant frame or shadow-DOM APIs.
An asynchronous callback times out
Cause: a fetch, timer, or application promise never resolves. Fix: add an in-page timeout with AbortController, set the automation timeout, and log the failing step. Also check whether the page blocks cross-origin requests.
Code disappears after navigation
Cause: evaluation-injected functions belong to the old document. Fix: register them after navigation, or use addInitScript() for pre-script setup and exposeFunction() for callbacks that must persist.
Performance, reliability, and cost considerations
Each evaluation crosses a process or protocol boundary. Batch related reads into one callback instead of issuing hundreds of individual evaluations. Return only the fields needed by the caller to reduce serialization overhead. For large result sets, consider extracting in pages or writing data to a controlled endpoint rather than transferring a huge object at once.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Evaluation itself does not establish a universal performance advantage for Playwright or Puppeteer. Reliability comes from deterministic waits, bounded timeouts, explicit arguments, and cleanup. Browser hosting, compute time, bandwidth, and any third-party service charges are separate from the API call; the reviewed documentation does not provide a general cost figure for running either library.
Or skip the browser setup
If your goal is a clean screenshot rather than arbitrary in-page computation, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status.
The API supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, device presets or custom viewports, retina scale, PDF paper and margin settings, custom CSS and JavaScript, clicks, selector or network-idle waits, request and resource blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, selectable cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work, which can simplify migration. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
Use the free plan for 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing gives two months free.
Recommended Free Tools
One-call example
See the complete option reference in the ScreenshotNeo documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Create a free ScreenshotNeo account to get 1,000 screenshots a month with no card.
Frequently Asked Questions
Can I call browser APIs such as localStorage inside an evaluated function?
Yes. The callback runs in the page context, so browser APIs available to that document can be read or changed, subject to the page’s origin and permissions.
Does page.evaluate() execute before network requests?
No. It executes when you call it against the current document. Use an initialization script for code that must be installed before the document’s own scripts run.
How can page code notify my Node.js process?
Expose a callback with Playwright’s page.exposeFunction(), then invoke that function from page JavaScript.
Should I use evaluation to replace normal locator APIs?
No. Prefer Playwright or Puppeteer locators and waits for interaction and synchronization; use evaluation when you specifically need DOM or browser-global access.
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.

