Use Playwright’s page.addScriptTag() to run custom JavaScript after a page loads, or page.addInitScript() to install code after document creation but before the site’s scripts run. Then capture the result with page.screenshot(). Choose the injection timing based on what your script needs to change, and wait for the page to reach the state you intend to capture.
What custom JavaScript can do before a screenshot
Custom JavaScript lets an automated browser change or inspect a page before taking a screenshot. Typical uses include setting a page marker, changing a visible state, dismissing an element for a test, or preparing a page-specific condition. The capture reflects the browser state after your script has run; it does not guarantee that a site’s asynchronous content, animations, or other dynamic behavior has settled.
The two main Playwright injection methods differ in timing:
page.addScriptTag()adds JavaScript to a page context, commonly after navigation. Use it when the document is already available and the target change can happen afterward.page.addInitScript()runs after the document is created but before the page’s own scripts. Use it when site scripts may otherwise overwrite or prevent the state you want to set. It also runs for newly attached or navigated child frames.
Neither method makes arbitrary changes work on every website. Results depend on the site, the page state, frames, authentication, and browser behavior.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errors#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.
Set up Playwright and capture a page
Install Playwright in a Node.js project, then install its Chromium browser. The example below is illustrative: adapt the URL, script, readiness condition, and output path to your target.
- Initialize a project and install Playwright:
npm init -y, thennpm install playwright. - Install Chromium with
npx playwright install chromium. - Save the following as
capture.jsand run it withnode capture.js.
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
try {
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'load' });
await page.addScriptTag({
content: `document.documentElement.dataset.captureReady = 'true';`
});
await page.screenshot({ path: 'capture.png', fullPage: true });
} finally {
await browser.close();
}
})();
The script sets a data attribute on the document element; it is an example of a page-context change, not a requirement for screenshotting. Replace the URL and script with the page and change you actually need. The official Playwright Page API documents injection and screenshot options.
Choose the right injection timing
Run code after navigation with addScriptTag
Use page.addScriptTag() when the page has loaded far enough for your script to find its target. Playwright supports adding a script from inline content or a file path. For example, a local script can be injected with await page.addScriptTag({ path: 'capture-setup.js' }). Keep the injection after navigation if it depends on page elements that do not exist before the document loads.
Be deliberate about readiness. A navigation event such as load does not prove that every application-specific request or lazy-loaded section is complete. If the change depends on a particular element, wait for that element before injecting:
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.
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
await page.locator('#main-content').waitFor();
await page.addScriptTag({ content: `
document.documentElement.dataset.captureReady = 'true';
` });
await page.screenshot({ path: 'capture.png', fullPage: true });
Use a selector that identifies the state relevant to your page rather than assuming a fixed delay will work everywhere.
Run code before the site’s scripts with addInitScript
When page scripts need to see a value from the beginning, register an init script before navigating:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
try {
const page = await browser.newPage();
await page.addInitScript(() => {
window.captureMode = true;
});
await page.goto('https://example.com');
await page.screenshot({ path: 'capture.png', fullPage: true });
} finally {
await browser.close();
}
})();
Playwright documents that init scripts run after document creation and before the page’s scripts. They are also evaluated in child frames when those frames are attached or navigated. This makes the method useful for early setup, but it does not guarantee that a site will use the value or that all frame behavior will match your expectations. Avoid putting secrets in page-context code.
Configure the screenshot itself
Playwright’s screenshot method can capture the viewport or the full scrollable page. Select options to match the output you need rather than assuming one capture mode fits every page.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
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.
- Full page: set
fullPage: trueto capture the full page rather than only the current viewport. - Output format: choose PNG, JPEG, or WebP through the output path or screenshot options documented by Playwright. Match the format to the next step in your workflow.
- Scale: choose CSS-pixel or device-pixel scaling when output dimensions matter.
- Masking: mask matching locators to obscure changing or sensitive regions in the screenshot.
- Stylesheet override: apply a stylesheet during capture when you need a controlled visual adjustment without making a persistent site change.
These controls shape the output; they do not automatically stabilize dynamic content. If a page animates, loads images lazily, or changes after a request completes, define an appropriate wait or page-specific preparation step before capturing.
Use another integration when it fits better
Playwright is a high-level browser automation option, but it is not the only route. The right choice depends on whether you are writing a browser automation script, working directly with the browser protocol, or building an extension.
| Approach | Best fit | Injection and capture route |
|---|---|---|
| Playwright | Page-level JavaScript browser automation | Use addScriptTag() or addInitScript(), then page.screenshot(). Official Page API. |
| Puppeteer | High-level JavaScript automation with Chrome or Firefox | Puppeteer supports browser automation tasks including screenshots and PDFs. See the Puppeteer overview for its scope. |
| Chrome DevTools Protocol (CDP) | Direct, lower-level browser protocol control | Use Page.addScriptToEvaluateOnNewDocument for scripts in frames before their scripts load, and Page.captureScreenshot to capture. See the CDP Page domain. |
| Chrome extension scripting | Injection managed by a Chrome extension | Chrome’s scripting API injects JavaScript or CSS into websites. Its documented default timing is document_idle, or immediate execution if the page has already loaded. See the Chrome scripting API. |
These interfaces operate at different integration levels; the documentation does not establish one universally superior method. Use Playwright or Puppeteer for a library-driven automation workflow, CDP when you need protocol-level commands, and extension scripting when the behavior belongs in an extension.
Troubleshoot common capture failures
The script runs but the screenshot looks unchanged
Check that your code targets the correct element and executes in the intended frame. If the site changes the same state afterward, run the script later or move setup that must precede site code into addInitScript(). Verify the condition in the page before taking the screenshot.
Recommended Free Tools
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
The script cannot find an element
The page may not have rendered the target yet, or the selector may not match the active page. Wait for a meaningful locator before injection. For content inside a frame, identify and work with that frame rather than assuming the top-level document contains the element.
The screenshot is incomplete or inconsistent
A navigation lifecycle event may occur before the content you care about is ready. Wait for a target selector or application-specific state. Full-page capture can include content beyond the viewport, but does not by itself promise that lazy images or other delayed content have finished loading.
The page behaves differently under automation
Sites can vary behavior based on browser context, login state, frames, or security controls. The cited APIs document injection capabilities, not successful modification of every site. Reproduce the needed authentication and browser conditions, and avoid assuming a script will bypass site security or access restrictions.
The process leaves a browser open after an error
Put browser shutdown in a finally block, as in the examples, so the browser is closed even if navigation, injection, or capture throws an error. Log or surface the original error as needed rather than silently treating a failed capture as a valid image.
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.
Performance, reliability, and cost considerations
A local Playwright workflow gives you control over browser launch, page context, injection timing, and capture settings. That control also means you manage browser installation, script failures, readiness logic, and output storage. A single fixed delay can make a script unnecessarily slow on quick pages and still too short on slow ones; a meaningful selector or state condition is generally more specific to the capture you need.
For recurring or large batches, consider how your own system will handle browser startup, timeouts, retries, and failures. The official API references describe available capabilities but do not establish a universal success rate, runtime, or cost for your target sites. Measure your own pages and workload before relying on a particular configuration.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server for developers. Instead of installing and managing a browser for a straightforward capture, send one GET request with the target URL. Its JavaScript option can run custom code before capture; the API also supports PNG, JPEG, WebP, and PDF output. See the ScreenshotNeo documentation for parameters and setup.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated 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 matchSign up for 1,000 free screenshots a month with no card.
Frequently asked questions
Can custom JavaScript make a screenshot capture a logged-in page?
The injection APIs do not themselves provide authentication. A capture must run in a browser context with the required login state and permissions.
Does full-page capture guarantee every lazy-loaded image appears?
No. Full-page mode selects the capture extent; it does not promise every delayed asset has loaded. Add page-specific readiness handling where needed.
Should I use Playwright or CDP?
Use Playwright for page-level automation through a library API. Use CDP when you need direct browser protocol commands. Their documented capabilities do not make either choice universally best.
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.

