How to Run PhantomJS Screenshots Reliably From a Cron Job
Run PhantomJS screenshots from a scheduled job with explicit paths, bounded waits, useful logs, and clear failure handling. Includes a legacy-runtime checklist and a no-browser-setup option.

To run PhantomJS screenshots reliably from cron, make the executable, script, working directory, environment, and log destination explicit. In the PhantomJS script, check the result of page.open, render only after a successful load, set a resource timeout, log failures, and always exit with an appropriate status. Then run the exact command from the scheduled environment and verify its output file.
PhantomJS is a legacy runtime: its official homepage says development is suspended until further notice. If you must keep an existing job, the steps below make its behavior easier to diagnose. If you are starting a new screenshot workflow, compare the cost of maintaining this runtime with a maintained capture option before building more around it.
1. Check PhantomJS and the host before scheduling
First confirm that PhantomJS runs on the machine that will own the scheduled job. The official download page identifies PhantomJS 2.1.1 and lists Linux binary dependencies, including Fontconfig and compatible GLIBC/GLIBCXX versions. These are dated project materials, so the version number alone does not prove that an archive will run on a current host.
command -v phantomjs
phantomjs --version
uname -a
Use the full path returned by command -v in the schedule. If PhantomJS is installed in a project-specific directory or container, use that installation path instead. Check dependencies on the actual host, not just a developer workstation. An interactive shell may have a different PATH, working directory, user, permissions, and environment from a scheduled process.
PhantomJS 1.5 and later is documented as pure headless and does not require X11 or Xvfb. On Linux, the official headless-testing page likewise describes operation without a GUI. That does not remove binary or font dependencies: install and verify what the chosen archive requires.
2. Create a script that reports page-load outcomes
Save this as an absolute path such as /opt/site-capture/capture.js. It accepts a URL, output filename, and optional viewport width and height. It sets a resource timeout, logs resource failures, checks the navigation status, renders only when the page reports success, and uses a nonzero exit code for a failed capture.

var page = require('webpage').create();
var system = require('system');
var args = system.args;
if (args.length < 4) {
console.log('Usage: phantomjs capture.js URL OUTPUT WIDTH HEIGHT');
phantom.exit(2);
}
var targetUrl = args[1];
var outputPath = args[2];
var width = parseInt(args[3], 10);
var height = parseInt(args[4], 10);
if (!targetUrl || !outputPath || !isFinite(width) || !isFinite(height) ||
width < 1 || height < 1) {
console.log('Invalid URL, output path, or viewport dimensions');
phantom.exit(2);
}
page.viewportSize = { width: width, height: height };
page.settings.resourceTimeout = 30000;
page.onResourceTimeout = function (request) {
console.log('RESOURCE_TIMEOUT ' + request.url + ' (' + request.errorCode + ')');
};
page.onResourceError = function (resourceError) {
console.log('RESOURCE_ERROR ' + resourceError.url + ': ' + resourceError.errorString);
};
page.onConsoleMessage = function (message) {
console.log('PAGE_CONSOLE ' + message);
};
page.open(targetUrl, function (status) {
if (status !== 'success') {
console.log('PAGE_OPEN_FAILED status=' + status + ' url=' + targetUrl);
phantom.exit(1);
return;
}
var rendered = page.render(outputPath);
if (rendered === false) {
console.log('RENDER_FAILED output=' + outputPath);
phantom.exit(1);
return;
}
console.log('CAPTURE_OK url=' + targetUrl + ' output=' + outputPath +
' viewport=' + width + 'x' + height);
phantom.exit(0);
});
The official quick start follows the same important pattern: inspect the page.open status, render after success, and call phantom.exit(). The explicit exit prevents a scheduled process from being left running by page activity. A successful navigation status means the page opened according to PhantomJS; it does not certify that every image, script, or application API succeeded. The resource callbacks help distinguish those cases.
The 30-second resource timeout above is an example, not a universal setting. Choose a limit based on the target’s normal response and the job’s deadline. The API documents resourceTimeout in milliseconds and says these settings apply during the initial page.open. Do not treat a short fixed sleep as proof that a page is ready. If the target renders important content asynchronously after navigation, add a page-specific readiness check and a bounded wait rather than assuming that the first paint contains the final state.
3. Choose the image dimensions and output deliberately
viewportSize sets the browser viewport, while clipRect can restrict the captured region. Decide whether the artifact should show a viewport-sized view or a specific rectangle, and use a stable viewport for repeatable layouts. The PhantomJS screenshot guide documents both controls.
PhantomJS can render PNG, JPEG, GIF, and PDF. Select the output extension and format to match the downstream consumer. PNG is a practical default for text and interface captures; JPEG is often smaller for photographic content but can blur fine text. For a PDF workflow, check the output on the scheduled host rather than assuming that a successful browser load means the final document is correct.
A fixed viewport does not guarantee identical pixels over time. Page content, fonts, remote assets, responsive breakpoints, animations, and third-party widgets can change. For a stable recurring capture, use a predictable target, pin the dimensions, and if necessary disable animation or wait for a page-specific element before rendering.
4. Run the exact command outside cron first
Before editing a crontab, execute the same command with the same account and paths that the scheduled job will use. Replace the example binary path with the result from your host and create the output directory in advance.
/usr/bin/phantomjs /opt/site-capture/capture.js \
https://example.com \
/var/tmp/example-shot.png \
1365 900
Verify the exit status and the actual file. A log line saying that a render was attempted is not a substitute for checking the artifact.
echo $?
ls -l /var/tmp/example-shot.png
file /var/tmp/example-shot.png
Use a directory the scheduled user can write to. If the script depends on a configuration file, certificates, fonts, or other assets, use absolute paths for those too. If it needs environment variables, define them deliberately in the job or a wrapper script rather than relying on an interactive shell startup file.
5. Add the schedule and preserve logs
Crontab syntax, shell behavior, and log handling vary by operating system and cron implementation. The following is an illustrative five-field cron entry for a daily run at 02:15. Confirm the syntax and logging destination supported by the host before using it.
15 2 * * * /usr/bin/phantomjs /opt/site-capture/capture.js https://example.com /var/tmp/example-shot.png 1365 900 >> /var/log/site-capture.log 2>&1
The redirection sends standard output and errors to one file and appends each run. Ensure the job’s user can write to that log. Set up rotation or another retention policy appropriate to the host so diagnostics do not fill a disk. Some systems route cron output through local mail or a service manager; use the platform’s normal mechanism if direct file redirection is unsuitable.
For a less crowded crontab, put the invocation and any required environment setup in an executable wrapper with a known interpreter, then schedule the wrapper by absolute path. A wrapper is also a good place to set a deliberate PATH, change to a known working directory, and record start and finish timestamps. Do not assume that a scheduled command begins in the project directory.
6. Diagnose failures by category
| Symptom | Likely cause | What to check |
|---|---|---|
phantomjs: not found |
The scheduled PATH does not include the install directory. | Use an absolute executable path and check it as the job user. |
| Permission denied or no output file | The job user cannot execute the binary or write the output directory. | Check file permissions, parent directory permissions, and the effective account. |
| Binary will not start on Linux | A required library or compatible GLIBC/GLIBCXX version may be missing. | Check the chosen PhantomJS archive’s documented requirements and inspect dependencies on the host. |
PAGE_OPEN_FAILED |
Navigation did not report success; network, DNS, TLS, proxy, or target availability may be involved. | Run with the same account and network path, inspect logs, and verify the URL is reachable from the host. |
RESOURCE_TIMEOUT |
A resource took longer than the configured millisecond limit. | Use the logged resource URL to identify a slow or unresponsive asset; adjust the timeout only if the job deadline allows it. |
| Screenshot is blank or incomplete | The page may have opened before asynchronous content appeared, or a required resource failed. | Inspect resource errors and add a bounded, page-specific readiness condition. |
| Works in terminal, fails on schedule | Different user, PATH, working directory, environment, permissions, or output destination. | Make paths and environment explicit; compare the scheduled account with the successful manual run. |
| Process hangs or overlaps the next run | A page or callback path may not exit, or a resource is taking too long. | Ensure every completion and error path exits; use finite resource limits and monitor duration. |
When the basic logs are not enough, PhantomJS documents CLI debug output and remote debugging options. Enable them temporarily and deliberately: verbose logs can contain URLs or other operational details. The CLI also accepts a JSON configuration file, along with command-line settings for options such as proxy and image loading. Prefer a configuration file when it makes the scheduled invocation easier to review, and check the CLI documentation for the exact option syntax of the installed version.

Be cautious with SSL-related switches. Disabling certificate checks can hide a certificate or interception problem and weaken security. First verify system time, certificate trust, proxy configuration, and the target’s certificate chain. Use any weakened security setting only when its implications are understood and the environment requires it.
7. Make repeated runs safer
A cron entry can start a second copy while the prior capture is still running if a page stalls or a run takes longer than expected. Use the host’s locking or job-control mechanism if overlapping captures would overwrite the same file or overload the target. Write to a temporary filename and rename it after a successful render if downstream readers must never see a partially written artifact.
For ongoing monitoring, log enough information to answer four questions: when did the run start, which URL did it try, did navigation and rendering succeed, and where is the output? Keep a nonzero process exit status for a failed capture so the host’s scheduler or monitoring can distinguish success from failure. Retain errors long enough to diagnose recurring problems, and periodically check that the output directory and logs have adequate space.
Do not infer reliability from one successful manual run. Test under the scheduled identity, test an unreachable URL, test a slow resource, and confirm that each case exits and leaves a useful diagnostic. These are operational checks, not a guarantee that a legacy browser will continue to render every modern site correctly.
8. Account for legacy support, performance, and cost
The official PhantomJS homepage says, “Important: PhantomJS development is suspended until further notice.” That status matters when a target site changes its JavaScript, TLS, or browser requirements: you may need to debug behavior without expecting a new PhantomJS release to address it. The official download and CLI materials identify version 2.1.1; confirm that the selected binary and its dependencies still work in your environment.
Performance depends on the target, network, page resources, viewport, and host. The research sources do not establish a representative runtime or success rate, so plan from measurements of your own pages and leave room in the schedule for slow loads. Set resource timeouts based on the job’s deadline. Loading fewer unnecessary resources may reduce work, but can also change the rendered page; use image-loading or proxy options only after confirming the result still meets the capture requirement.
PhantomJS is distributed as a software archive, and cron is an operating-system facility; no task-specific service charge or benchmark is established by the sources for this workflow. Your practical costs are the time spent maintaining the binary and dependencies, the machine resources used by scheduled runs, and the cost of missed or incorrect captures. Include those costs when deciding whether to keep the current job or migrate.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. Instead of installing and maintaining a headless browser for a simple capture, make one GET request. See the ScreenshotNeo API documentation for request options and details.
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://example.com \
-o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://example.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://example.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write('shot.webp', res);
ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; 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 offers take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Every feature is on every plan.
Start free with 1,000 screenshots a month and no card.
Frequently asked questions
Does PhantomJS require Xvfb for a cron job?
According to the official FAQ, PhantomJS has been pure headless since version 1.5 and does not require X11/Xvfb. Verify the binary and dependencies on the host where the job runs.
Can I use a JSON file for PhantomJS options?
Yes. The CLI documentation describes JSON configuration as well as command-line options. Use the documentation that matches the installed binary to confirm option names and precedence.
Does a successful page.open prove that the screenshot is complete?
No. It reports navigation status. A page can still have failed resources or content that appears asynchronously, so inspect resource callbacks and wait for a page-specific readiness signal when needed.
Should a new screenshot job use PhantomJS?
PhantomJS development is suspended. For an existing dependency, test compatibility and account for maintenance work. For a new job, compare current options against your browser, rendering, and support requirements before committing to a legacy runtime.


