How to Capture JavaScript-Heavy Websites with PhantomJS
Use PhantomJS to open a page, wait for its JavaScript content, and save a screenshot. Learn how to handle timing, dimensions, formats, common failures, and PhantomJS’s legacy status.

To capture a JavaScript-heavy website with PhantomJS, open the page with page.open, check its load status, wait until the content you need is ready, and then call page.render. PhantomJS executes page JavaScript by default, but the page-load callback does not guarantee that a modern single-page application has finished its later asynchronous updates. Set a deliberate wait or check for a page-specific readiness condition before rendering.
PhantomJS is a legacy choice: its project says development is suspended, and its repository is archived. The steps below describe the documented workflow; they do not guarantee compatibility with every current site. Verify the result against the exact page you need to capture.
1. Install and run PhantomJS
PhantomJS is a command-line browser. The official Quick Start uses a JavaScript file as its input and runs it with the phantomjs executable. Install an available PhantomJS build using the instructions appropriate to your operating system, then make sure the executable is on your PATH. The project identifies 2.1 as its latest stable release; its sources do not establish a current release or support plan.
Save the script in the next section as capture.js. From a terminal in that directory, run:
phantomjs capture.js
The script writes the image to its configured output path. If the command is not found, the executable is either not installed or not on PATH. You can instead invoke it using its full filesystem path.
2. Capture a page after its JavaScript content is ready
This complete example opens a target page, waits for a known element that the page adds after its initial load, and saves a PNG. Change the URL and selector to match the page. The selector must identify content that appears only when the content you need is ready; a selector that exists in the initial HTML does not tell you whether later data has loaded.

var page = require('webpage').create();
var system = require('system');
var targetUrl = system.args[1] || 'https://example.com';
var readySelector = system.args[2] || '#main-content';
var outputPath = system.args[3] || 'capture.png';
var maxWaitMs = 15000;
var pollIntervalMs = 250;
var startedAt;
page.viewportSize = { width: 1280, height: 900 };
page.open(targetUrl, function (status) {
if (status !== 'success') {
console.log('Failed to load the page: ' + targetUrl);
phantom.exit(1);
return;
}
startedAt = Date.now();
waitForReady();
});
function waitForReady() {
var ready = page.evaluate(function (selector) {
var element = document.querySelector(selector);
return !!element && element.getClientRects().length > 0;
}, readySelector);
if (ready) {
page.render(outputPath);
console.log('Saved ' + outputPath);
phantom.exit(0);
return;
}
if (Date.now() - startedAt >= maxWaitMs) {
console.log('Timed out waiting for selector: ' + readySelector);
phantom.exit(2);
return;
}
setTimeout(waitForReady, pollIntervalMs);
}
Run it with optional arguments for the URL, readiness selector, and destination:
phantomjs capture.js 'https://example.com' '#main-content' 'capture.png'
The selector polling is an implementation approach using PhantomJS’s page JavaScript evaluation and timers. It is not a universal PhantomJS application-readiness feature. If the page does not expose a stable element or state that indicates completion, use a fixed delay and inspect the output. A fixed delay can be too short when the page is slow and waste time when it is fast.
3. Understand page loading and wait strategy
The page.open(url, callback) callback reports whether the page load succeeded. It is useful for catching a failed load before rendering, but load completion alone does not prove that later application work has finished. A site may fetch data after the initial document load, update the DOM, lazy-load images as you scroll, or show a consent dialog after a delay.
| Strategy | Use it when | Trade-off |
|---|---|---|
| Render immediately in the load callback | The page is static or its needed content is already present at load completion. | Fast, but may capture before delayed updates. |
| Fixed delay | You know roughly when a particular page normally finishes its updates and need a simple script. | May be too short on a slow run, or longer than necessary. |
| Page-specific readiness check | A target element or page state reliably signals that the content you need is available. | More dependable for that page, but requires a meaningful condition and a timeout. |
The PhantomJS project homepage illustrates waiting briefly after opening a page before capture. Treat that as an example, not a recommended duration for every site. There is no wait value that can be inferred as universal from the project documentation.
For a simple fixed wait, schedule the render after the load callback:
page.open('https://example.com', function (status) {
if (status !== 'success') {
console.log('Failed to load the page');
phantom.exit(1);
return;
}
window.setTimeout(function () {
page.render('capture.png');
phantom.exit();
}, 3000);
});
Adjust the delay based on the target page and the content you need. For repeatable captures, prefer a page-specific condition and a maximum wait so a missing element cannot leave the command running indefinitely.
4. Set page settings before opening
Configure the viewport and any relevant page settings before calling page.open. PhantomJS documents settings including JavaScript enablement, image loading, the user agent, resource timeout, and web security. These settings apply during the initial page-open operation.
var page = require('webpage').create();
page.viewportSize = { width: 1440, height: 1000 };
page.settings.javascriptEnabled = true;
page.settings.loadImages = true;
page.settings.userAgent = 'Mozilla/5.0 (compatible; CaptureScript/1.0)';
page.settings.resourceTimeout = 20000;
page.open('https://example.com', function (status) {
if (status !== 'success') {
console.log('Failed to load the page');
phantom.exit(1);
return;
}
window.setTimeout(function () {
page.render('capture.png');
phantom.exit();
}, 3000);
});
Keep the user agent truthful and appropriate for your use. A resource timeout limits how long an individual requested resource can take before PhantomJS stops waiting for it. It does not mean that the whole page has completed its application-level work, and it is not a substitute for a readiness check. Missing or slow scripts, fonts, or images can change the captured result.
JavaScript is enabled by default in the documented settings. Turning it off prevents JavaScript-driven content from rendering as intended. Likewise, disabling image loading may make the capture incomplete. Do not routinely disable web security or ignore TLS problems to make a screenshot work: those choices can change the behavior and security assumptions of the page. Investigate the failed resource or certificate issue instead.
5. Choose viewport, capture region, and format
page.viewportSize sets the browser viewport. It affects responsive breakpoints and the layout a site chooses, so match the dimensions to the intended desktop or mobile presentation. It is not simply a request for an image of that exact size: a full page may extend beyond the viewport.

Use page.clipRect when you want a particular rectangle rather than the whole rendered page:
page.viewportSize = { width: 1280, height: 900 };
page.clipRect = { top: 100, left: 40, width: 800, height: 500 };
page.render('region.png');
The rectangle is measured in page coordinates. Check that it lies within the intended content and account for fixed headers or overlays. For full-page capture, omit the clip rectangle and use the documented render behavior supported by your PhantomJS build; inspect long pages for content that only appears after scrolling or lazy loading.
| Output | When it fits | Consideration |
|---|---|---|
| PNG | Interface screenshots, text, diagrams, and lossless output. | Can produce larger files than lossy photographic formats. |
| JPEG | Photographic pages where a smaller lossy image is acceptable. | Compression can blur text and sharp edges; quality can be configured. |
| A document-style artifact or page intended for printing. | Check page size, pagination, and whether the result matches the intended document. | |
| BMP or PPM | Specific workflows that require these documented raster formats. | Usually less convenient for web delivery than PNG or JPEG. |
The output filename extension selects the rendering format. The API documents PDF, PNG, JPEG, BMP, and PPM; GIF support depends on the Qt build. JPEG quality and PNG compression options are also documented. Example filenames include capture.jpg and capture.pdf. The screen-capture guide describes rendering SVG, images, and Canvas content, but that describes the legacy stack’s documented capability, not compatibility with every modern page or resource.
6. Troubleshoot common capture problems
| Symptom | Likely cause | What to do |
|---|---|---|
| Blank or incomplete screenshot | The page did not load successfully, or rendering happened before asynchronous content appeared. | Check the page.open status. Add a page-specific readiness check or a bounded delay, then verify that the selector actually represents the needed content. |
| Dynamic data is missing | The application updates after the load callback, or its data request failed. | Wait for a meaningful DOM condition. Check whether the relevant element is present and visible, and inspect any page errors or failed resources available to your script. |
| Images or fonts are missing | Resources are disabled, slow, unavailable, or blocked by the target page. | Confirm image loading is enabled. Review the resource timeout and the actual resource response; increasing the timeout only helps if a resource is simply slow. |
| Layout differs from the expected device | The viewport triggers another responsive breakpoint. | Set page.viewportSize before opening the URL and use dimensions that match the desired presentation. |
| Only part of the page is visible | A clip rectangle constrains the capture, or the requested full-page behavior is not suitable for the page. | Review page.clipRect coordinates. For lazy content, the page may need scrolling or a page-specific approach before rendering. |
| The script never exits | A callback path does not call phantom.exit(), or a wait has no timeout. |
Ensure every success and failure path exits. Put a maximum duration on polling and return a nonzero exit code when readiness times out. |
| The command is not found | The PhantomJS executable is absent or not on PATH. |
Install an available build or invoke the executable by its full path. |
| A current site renders incorrectly | The archived browser stack may not support the site’s current browser features or resources. | Confirm the issue against the target site and consider a maintained browser automation option if modern web compatibility is required. |
7. Performance, reliability, and cost
Capture time includes navigation, requested resources, any wait you add, and image or PDF rendering. A longer fixed wait directly adds time even when the page becomes ready sooner. A short wait can yield inconsistent output if the site’s response varies. A bounded readiness check helps avoid both an unbounded wait and a premature render, provided the condition is meaningful.
For repeat runs, use the same viewport, URL, readiness condition, and output settings. Keep resource timeouts suited to the pages you capture, and treat a failed load or readiness timeout as an explicit failure rather than silently saving an empty file. PhantomJS being archived means readers should account for browser compatibility and maintenance risk in any ongoing workflow; the cited sources do not provide current compatibility guarantees.
The PhantomJS workflow runs locally or wherever you have installed its executable, so the direct cost depends on your own compute and operations. The dossier establishes no benchmark, hosting price, or current support commitment. If you capture pages at scale, account for process management, retries, output storage, and the time needed to diagnose changing target pages.
8. Or skip the browser setup
If you need an API call instead of managing a local PhantomJS browser, ScreenshotNeo is a website screenshot API and MCP server. It returns a screenshot or PDF from one GET request. See the ScreenshotNeo API documentation for its 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}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer())));
ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot; each cleanup step can be turned off. Bot checks, blank pages, and failed loads are never billed, and response headers report the page verdict and billing status. Its MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.
Sign up free for 1,000 screenshots a month, with no card required.
9. Frequently asked questions
Does PhantomJS run JavaScript?
Yes. JavaScript is enabled by default in its documented page settings. That does not mean every asynchronous update is complete when the page-open callback runs.
Can PhantomJS capture a PDF?
The page.render API documents PDF output selected through the filename extension. Check page layout and pagination in the generated document.
Is PhantomJS still maintained?
The project says development is suspended, and its GitHub repository was archived on May 30, 2023. Treat it as a legacy tool and validate it against your target pages.
Is a fixed delay always necessary?
No. Render after load when the needed content is already present. Add a wait only when the target page’s behavior requires it, and make the wait condition or duration specific to that page.
Primary references
- PhantomJS Quick Start: command-line invocation and the open, render, and exit flow.
- PhantomJS page.open API and page.render API: callback and output behavior.
- PhantomJS webpage settings: JavaScript, images, user agent, resource timeout, and security settings.
- PhantomJS screen capture guide: viewport and clipping examples.
- PhantomJS project homepage and GitHub repository: suspended development and archived project status.


