How to Automate React Application Screenshots with PhantomJS or Webshot
Capture React routes reliably with PhantomJS, R webshot, or node-webshot—waiting for rendering, selecting elements, and handling CI failures.

Short answer: open the React route, wait until client-side rendering and assets settle, then capture the viewport, full page, CSS selector, or explicit rectangle. PhantomJS provides the underlying page.open() and page.render() workflow; R webshot and node-webshot add delays, selectors, callbacks, JavaScript evaluation, cookies, headers, CSS, and other capture controls. Because PhantomJS uses a legacy WebKit engine, validate the exact React build, browser APIs, fonts, and CSS used by your application before depending on it in CI.
1. Choose the capture approach
| Approach | Best for | Important limitation |
|---|---|---|
| PhantomJS | A small JavaScript script with direct control over a page object | Legacy WebKit compatibility must be checked against a modern React build |
| R webshot | R reports, visual checks, and scripts that already use R | Requires PhantomJS and exposes the same legacy rendering boundary |
| node-webshot | Node automation with callbacks, streams, and PhantomJS options | The npm package is old (version 0.18.0; the listing identifies an 11-year-old publication), so pin dependencies and test your target build |
| Hosted capture API | Teams that do not want to maintain a PhantomJS runtime | Review security, data handling, pricing, and service terms before production use |
The PhantomJS screen-capture documentation shows the minimal open-and-render sequence. The webshot reference documents delays, clipping, selectors, zoom, JavaScript evaluation, and user agents. The node-webshot package documentation covers viewport and full-page sizing, cookies, headers, CSS, render delays, callbacks, and selector capture.
2. Minimal PhantomJS screenshot
Save this as capture.js. It opens a route, renders a PNG, and exits only after the callback runs.
var page = require('webpage').create();
page.open('http://localhost:3000/dashboard', function (status) {
if (status !== 'success') {
console.error('Could not open route: ' + status);
phantom.exit(1);
return;
}
page.render('dashboard.png');
phantom.exit();
});
Run it with the PhantomJS executable:
phantomjs capture.js
PhantomJS can render PNG, JPEG, GIF, and PDF. Set page.viewportSize for the browser viewport and page.clipRect for a manually defined capture rectangle.
3. Wait for React to render before capturing
page.open() means the initial document loaded; it does not prove that React finished fetching data, loading images, applying fonts, or completing animations. Use a deliberate delay, a polling loop, or a page-side flag.

Fixed delay
var page = require('webpage').create();
page.viewportSize = { width: 1440, height: 900 };
page.open('http://localhost:3000/reports/42', function (status) {
if (status !== 'success') {
phantom.exit(1);
return;
}
window.setTimeout(function () {
page.render('report.png');
phantom.exit();
}, 1500);
});
A fixed delay is simple but can be too short on a busy CI runner and waste time on a fast route.
Poll for an application-ready marker
Add a marker to the React application after the data and layout needed for the shot are ready, for example <main data-screenshot-ready="true">. Then poll it from PhantomJS:
var page = require('webpage').create();
page.viewportSize = { width: 1440, height: 900 };
var started = Date.now();
var timeoutMs = 15000;
function finish(statusCode) {
phantom.exit(statusCode || 0);
}
function pollReady() {
var ready = page.evaluate(function () {
var marker = document.querySelector('[data-screenshot-ready="true"]');
return !!marker;
});
if (ready) {
page.render('ready-report.png');
finish(0);
return;
}
if (Date.now() - started > timeoutMs) {
console.error('Timed out waiting for data-screenshot-ready');
finish(1);
return;
}
window.setTimeout(pollReady, 100);
}
page.open('http://localhost:3000/reports/42', function (status) {
if (status !== 'success') {
console.error('Open failed: ' + status);
finish(1);
return;
}
pollReady();
});
Prepare the page with JavaScript
Use page.evaluate() to hide a loading layer, freeze an animation, or set a state that is safe for visual capture. The function runs inside the page and can return serializable values.
page.evaluate(function () {
var style = document.createElement('style');
style.textContent = '* { animation: none !important; transition: none !important; }';
document.head.appendChild(style);
var loading = document.querySelector('.loading-overlay');
if (loading) loading.style.display = 'none';
});
4. Viewport, full-page, element, and rectangle captures
Viewport capture
page.viewportSize = { width: 1280, height: 720 };
page.render('viewport.png');
This captures what fits inside the configured viewport.
Full-page capture
PhantomJS itself exposes the page object and clipping primitives rather than a universal full-page switch. A common approach is to measure the document and set a clip rectangle before rendering:
var size = page.evaluate(function () {
return {
width: Math.max(document.body.scrollWidth, document.documentElement.scrollWidth),
height: Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
};
});
page.clipRect = { top: 0, left: 0, width: size.width, height: size.height };
page.render('full-page.png');
Very tall pages can exceed memory or image-format limits. Split long documents into sections when a single bitmap is impractical.
Capture an element
Measure the element’s bounding rectangle in the page, then assign it to clipRect:
var rect = page.evaluate(function () {
var node = document.querySelector('[data-testid="invoice"]');
if (!node) return null;
var r = node.getBoundingClientRect();
return {
left: r.left + window.pageXOffset,
top: r.top + window.pageYOffset,
width: r.width,
height: r.height
};
});
if (!rect) {
console.error('Element not found');
phantom.exit(1);
} else {
page.clipRect = rect;
page.render('invoice.png');
phantom.exit();
}
Ensure the element is visible and has non-zero dimensions. For a selector whose height changes after images load, wait for the final layout before measuring it.
5. R webshot for React routes
Install PhantomJS first, then install the R package. The package’s introduction uses webshot(URL, delay = 0.5).
install.packages("webshot")
webshot::install_phantomjs()
Basic delayed capture:
library(webshot)
webshot(
url = "http://localhost:3000/dashboard",
file = "dashboard.png",
vwidth = 1440,
vheight = 900,
delay = 1.5
)
Element capture, zoom, a user agent, and JavaScript evaluation:
library(webshot)
webshot(
url = "http://localhost:3000/reports/42",
file = "report-card.png",
selector = ".report-card",
expand = TRUE,
vwidth = 1280,
vheight = 900,
zoom = 1,
delay = 1,
useragent = "screenshot-ci/1.0",
eval = "document.body.classList.add('screenshot-mode');"
)
Relevant webshot controls include:
| Option | Use |
|---|---|
vwidth, vheight |
Set the viewport dimensions |
cliprect |
Capture an explicit rectangle |
selector |
Capture a CSS-selected element |
expand |
Expand a selected element’s capture area |
delay |
Wait after navigation before rendering |
zoom |
Scale the rendered result |
eval |
Run JavaScript before capture |
useragent |
Supply a custom user-agent string |
debug |
Help diagnose PhantomJS rendering problems |
6. Node.js webshot
Install and pin the package because its published release is old:
npm install --save-exact webshot@0.18.0
This example captures an element after React has had time to render:
const webshot = require('webshot');
const options = {
windowSize: { width: 1440, height: 900 },
shotSize: { width: 'all', height: 'all' },
renderDelay: 1500,
userAgent: 'screenshot-ci/1.0',
selector: '.report-card',
customCSS: '.loading-overlay { display: none !important; }'
};
webshot(
'http://localhost:3000/reports/42',
'report-card.png',
options,
function (error) {
if (error) {
console.error(error);
process.exitCode = 1;
return;
}
console.log('Saved report-card.png');
}
);
For a viewport-sized image, use matching windowSize and shotSize values:
const webshot = require('webshot');
webshot('http://localhost:3000/', 'home.png', {
windowSize: { width: 1280, height: 720 },
shotSize: { width: 1280, height: 720 },
renderDelay: 1000
}, function (error) {
if (error) process.exitCode = 1;
});
Node webshot can capture a URL, local file, or inline HTML, and can stream image output. Its options include viewport and full-page sizing, user agents, cookies, custom headers, custom CSS, render delays, callbacks, and selector capture.
7. Authentication, headers, cookies, and routing
Protected React routes often return a shell that cannot load data unless the request has the same identity and headers as a real browser session. Supply cookies or headers through the wrapper you use, or create a test-only route that establishes the session before capture.
- Use cookies for an existing authenticated session.
- Use custom headers for API keys or tenant headers required by the route.
- Set a user agent when responsive rendering or server-side behavior depends on it.
- Open the final client-side route directly and configure the server to serve the React app for that path.
- Wait for the route’s data request and images, not merely the initial HTML document.
Never place production secrets in source files committed to a repository. Inject CI values through the job environment and limit the account used for screenshots.
8. Make captures deterministic in CI
- Pin PhantomJS, webshot, node-webshot, and the Node or R runtime.
- Use a fixed viewport and a fixed device scale or zoom.
- Disable CSS transitions, animations, carousels, blinking cursors, and time-dependent content.
- Use stable fixture data and a deterministic timezone.
- Wait for a route-specific ready marker or a known selector.
- Preload or bundle fonts when possible; missing fonts change line wrapping and element dimensions.
- Capture after lazy images have loaded and after the final layout measurement.
- Compare images with a tolerance for anti-aliasing differences rather than exact bytes.
PhantomJS uses WebKit, so modern React syntax may work only after transpilation and some browser APIs or CSS features may be unsupported. There is no central compatibility matrix in the reviewed documentation; test the actual production build and target routes.
9. Troubleshooting common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Blank white image | JavaScript error, unsupported browser API, or capture before React mounts | Check PhantomJS console output, transpile the bundle, add a readiness wait, and verify the route in the target runtime |
| Loading spinner in the image | Data request or lazy component was still pending | Wait for a selector or application-ready marker instead of relying on navigation completion |
| Wrong route or 404 | Server does not rewrite a client-side route to the React entry document | Configure the test server fallback or capture the entry route before navigating inside the app |
| Missing authenticated content | Cookies or required headers were not supplied | Pass the session cookie and headers, or use a controlled test account |
| Element not found | Selector changed, component has not mounted, or the element is inside an unsupported frame | Verify the selector, wait for it, and inspect whether the content is rendered in an iframe |
| Clipped element | Bounding rectangle was measured before fonts or images settled | Wait for final layout, then calculate the rectangle and include scroll offsets |
| Fonts or icons differ | Font request failed or the font was not installed in CI | Bundle or preload fonts, allow them to load before capture, and use the same font files in CI |
| Intermittent timeouts | Fixed delay is too short or the runner is overloaded | Use polling with a timeout, log page errors, and avoid unlimited retries |
| Modern page fails to render | Legacy PhantomJS WebKit lacks a required API or CSS feature | Reduce the target bundle to supported features or use a maintained browser-based capture service |
10. Performance, reliability, and cost considerations
- Wait strategy: selector polling usually finishes sooner than a large fixed delay, while a timeout prevents hung jobs.
- Page size: full-page captures consume more memory than viewport or element shots; split very long pages.
- Parallelism: run a bounded number of PhantomJS workers so CPU and memory pressure do not create false failures.
- Network: serve test assets locally or from a stable environment; third-party ads, analytics, and chat scripts add nondeterminism.
- Caching: cache dependencies and the PhantomJS binary in CI, but keep application data deterministic.
- Retries: retry transient navigation failures only after recording the status and console error; retries cannot fix unsupported browser features.
- Cost: local PhantomJS has no per-shot API fee, but it carries maintenance and CI infrastructure costs. Hosted services trade that maintenance for service, security, and usage pricing that must be evaluated directly.
11. Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. It accepts one GET request and returns PNG, JPEG, WebP, or PDF. The API can wait for selectors, delays, or network idle; capture full pages or CSS-selected elements; set viewport, device presets, retina scale, cookies, headers, user agent, timezone, geolocation, custom CSS, and JavaScript; block ads, trackers, requests, or resource types; and create PDFs, async jobs, signed links, or bulk captures. See the ScreenshotNeo API documentation for request options.

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}`);
Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
12. Frequently asked questions
Does PhantomJS wait for React automatically?
No. It waits for the page-open callback; add a delay, selector poll, or page-side readiness signal for asynchronous rendering.
Can I capture only one React component?
Yes. Use a CSS selector in webshot or node-webshot, or measure the component and assign its rectangle to PhantomJS clipRect.
Should I use a fixed delay or a readiness marker?
A readiness marker is generally more efficient and reliable because it reflects the route’s actual state. Keep a maximum timeout so a broken request cannot hang CI.
Why does a screenshot differ between local and CI?
Compare viewport, fonts, device scale, timezone, data, network responses, animations, and the exact PhantomJS and wrapper versions. Legacy WebKit differences can also change layout.
When should I move away from PhantomJS?
Move when the React build depends on browser APIs, CSS, fonts, or JavaScript syntax that PhantomJS cannot render reliably, or when maintaining the runtime costs more than using a hosted capture service.


