How to Fix PhantomJS Hanging When Run From the CLI or Web
Diagnose PhantomJS hangs with explicit exits, resource logging, HTTPS and proxy checks, watchdogs, and a practical migration path.

Short answer: a PhantomJS “hang” usually means one of three things: the script never calls phantom.exit(), a page or individual resource never reaches a terminal state, or an error is occurring but no callback logs it. Confirm the binary, add explicit completion paths, instrument page and resource callbacks, then check HTTPS, proxy, and page JavaScript errors. PhantomJS is archived and unmaintained, so treat these steps as legacy triage and plan a migration when browser compatibility matters.
1. Identify which layer is stuck
Separate the symptom before changing timeouts. A process that remains after a successful render is a lifecycle problem. A process waiting inside page.open is a page or network problem. A page that reports success but never produces the expected output can be blocked by page JavaScript, a selector wait, or an exception hidden from the terminal.

| What you observe | Likely layer | First evidence to collect |
|---|---|---|
| Image is written, command never returns | Process lifecycle | Look for a missing phantom.exit() |
No page.open callback |
Network/resource lifecycle | Resource request, timeout, and error logs |
Callback says fail |
Transport or target page | URL, error string, HTTPS/proxy settings |
Callback says success, output is wrong |
Page JavaScript or timing | page.onError, console output, render timing |
2. Verify the executable and command line
Start by recording the exact binary your shell invokes. Conflicting installations can make a terminal run a different version than the one you inspected. The PhantomJS CLI syntax is phantomjs [options] somescript.js [arg1 ...]; the legacy command-line reference targets 2.1.1 unless noted.
# Record version and path
phantomjs --version
command -v phantomjs
# Run with additional diagnostics
phantomjs --debug=true capture.js https://example.com
# On Windows, print the resolved executable
where phantomjs
If the version or path differs between an interactive shell, a service, and a web worker, fix that first. Log the working directory and environment too; relative output paths and proxy variables often differ between CLI and web execution.
3. Make every terminal path call phantom.exit()
The quick start explicitly warns that PhantomJS is not terminated unless the script calls phantom.exit. Call it after the final asynchronous operation, and call it for both success and failure. Do not place it immediately after page.open(), because that exits before the callback runs.
var page = require('webpage').create();
var system = require('system');
var address = system.args[1] || 'https://example.com';
var output = system.args[2] || 'shot.png';
function finish(code) {
// Keep one deliberate shutdown path.
phantom.exit(code || 0);
}
page.open(address, function (status) {
console.log('page.open status: ' + status);
if (status !== 'success') {
finish(1);
return;
}
page.render(output);
console.log('saved ' + output);
finish(0);
});
When you add more asynchronous work (for example, a delayed render), move finish() to the last callback. If an exception can bypass your callback, add a global handler:
phantom.onError = function (message, trace) {
console.log('phantom error: ' + message);
trace.forEach(function (item) {
console.log(' ' + item.file + ':' + item.line + ' in ' + item.function);
});
phantom.exit(1);
};
4. Instrument page, network, and console callbacks
page.open invokes its callback when loading finishes, and the load result is success or fail. Log that value. Add the resource handlers below to discover a single stalled request, a DNS/TLS failure, or a page exception that otherwise looks like a freeze.
var page = require('webpage').create();
var system = require('system');
var address = system.args[1] || 'https://example.com';
// Milliseconds, per requested resource. Set before page.open.
page.settings.resourceTimeout = 10000;
page.onResourceRequested = function (request) {
console.log('[request] ' + request.id + ' ' + request.url);
};
page.onResourceTimeout = function (request) {
console.log('[timeout] ' + request.id + ' ' + request.url);
console.log(' ' + request.errorString);
};
page.onResourceError = function (error) {
console.log('[resource error] ' + error.url + ' ' + error.errorString);
};
page.onError = function (message, trace) {
console.log('[page error] ' + message);
trace.forEach(function (item) {
console.log(' ' + item.file + ':' + item.line);
});
};
page.onConsoleMessage = function (message) {
console.log('[console] ' + message);
};
page.open(address, function (status) {
console.log('[load finished] ' + status);
phantom.exit(status === 'success' ? 0 : 1);
});
resourceTimeout is a bound for each requested resource, measured in milliseconds. Configure it before the initial page.open; changing it later does not alter that open. It is not a whole-script deadline, and it does not stop an infinite JavaScript loop or guarantee that the process exits.
5. Check HTTPS, proxies, and host policy
If the same URL works over HTTP but hangs or fails over HTTPS, follow the official troubleshooting guidance and inspect the SSL libraries, usually OpenSSL. Verify the library versions visible to the PhantomJS process rather than only those installed for another runtime.
On Windows, the default proxy can introduce very large latency. Test a run with the proxy disabled:
phantomjs --proxy-type=none capture.js https://example.com
Only keep this setting if it matches your network policy. In Linux environments, SELinux can also block an otherwise valid binary. Check audit or denial logs first and apply an environment-specific policy adjustment only after confirming that SELinux is the cause.
6. Use the remote debugger for a page-specific hang
For code that stalls inside page JavaScript, start PhantomJS with its remote debugger and inspect the page in a WebKit-based browser such as Chrome, Chromium, or Safari. The official troubleshooting guide documents port 9000:
phantomjs --remote-debugger-port=9000 capture.js https://example.com
Attach the debugger, inspect the console and call stack, and look for synchronous loops, promises that never settle, or code waiting on a browser API PhantomJS does not implement. Also remember that page console messages are silent by default; page.onConsoleMessage makes them visible.
7. Add a wall-clock watchdog when you need a hard job limit
Because resourceTimeout is per resource, a page with many requests can still run for a long time. A watchdog gives your wrapper a total limit while preserving the normal load callback.
var page = require('webpage').create();
var done = false;
var watchdog = setTimeout(function () {
if (done) { return; }
console.log('watchdog: total job deadline reached');
done = true;
phantom.exit(2);
}, 30000);
page.settings.resourceTimeout = 10000;
page.open('https://example.com', function (status) {
if (done) { return; }
done = true;
clearTimeout(watchdog);
console.log(status);
phantom.exit(status === 'success' ? 0 : 1);
});
Use a guard such as done so a late callback cannot perform work after the watchdog exits. Choose the deadline from your page and network requirements; the value above is an example, not a PhantomJS default.
8. Common errors and fixes
| Message or symptom | Cause | Fix |
|---|---|---|
| Rendered file exists, process stays alive | No explicit shutdown | Call phantom.exit(0) after rendering and on every failure path. |
page.open never logs |
Request still pending or callback instrumentation missing | Set resourceTimeout before open; add request, timeout, and error handlers. |
status: fail |
DNS, TLS, proxy, certificate, or server failure | Log resource errors; compare HTTP/HTTPS; test Windows with --proxy-type=none. |
| HTTPS only hangs | SSL library mismatch or TLS incompatibility | Check OpenSSL and the libraries loaded by PhantomJS; test the target from the same host. |
| Success but blank or incomplete image | Render occurred before app content or lazy assets were ready | Wait for a known condition with a bounded delay, then render; inspect console and page errors. |
| Terminal appears frozen with no errors | Page exception or console output is hidden | Add page.onError, phantom.onError, and onConsoleMessage. |
| Huge delay only on Windows | Default proxy behavior | Try --proxy-type=none and compare timings. |
| Works in one shell, not a service | Different binary, environment, permissions, or working directory | Log command -v/where, version, cwd, and environment in both contexts. |
9. CLI versus web invocation
A web endpoint should not hold an HTTP request open indefinitely while PhantomJS waits. Put the capture in a worker, enforce a process deadline, stream logs to a job record, and return a job ID or a bounded error. Sanitize the URL and output path, cap concurrent PhantomJS processes, and kill a child that exceeds the wall-clock limit. The browser process should be treated as disposable: a timeout or crash must not poison the next job.
For a direct CLI wrapper, propagate exit codes so automation can distinguish success, page failure, and watchdog termination:
#!/usr/bin/env bash
set -eu
url="${1:?URL required}"
out="${2:-shot.png}"
timeout 45s phantomjs capture.js "$url" "$out"
case "$?" in
0) echo "capture ok" ;;
124) echo "capture exceeded wall-clock limit" >&2; exit 124 ;;
*) echo "capture failed" >&2; exit 1 ;;
esac
The shell timeout is an outer guard; keep the in-script watchdog as well if you need a diagnostic exit code and a final log line.
10. Reliability, performance, and cost considerations
- Reliability: log the URL, PhantomJS version, status, resource errors, and exit code for every job. Retain a small failing HTML fixture so a dependency update can be compared.
- Performance: resource logging is valuable during diagnosis but noisy in production. Disable verbose request logs after the cause is known, and limit concurrency to the CPU and memory available.
- Timeouts: use a per-resource timeout plus a total wall-clock deadline. A single setting cannot cover DNS, many assets, page loops, and process shutdown.
- Maintenance: the upstream repository is archived and read-only; its README says development is suspended, and the wiki describes the 2.x branch as deprecated and unmaintained. Legacy fixes can keep a known job running, but ongoing browser compatibility argues for migration.
- Cost: PhantomJS itself does not solve infrastructure costs. Account for worker CPU, memory, queue time, proxy traffic, and operational work when comparing a self-hosted setup with a screenshot service.
See the primary references for Troubleshooting, Quick Start, WebPage settings, CLI options, page.open, onLoadFinished, onResourceTimeout, onResourceError, onResourceRequested, and render.
11. Or skip the browser setup
If your goal is a dependable screenshot rather than maintaining a PhantomJS process, ScreenshotNeo provides a GET API and an MCP server. It accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms plus newsletter popups and chat widgets before capture; 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 the response identifies the result with X-Page-Verdict and X-Billed headers.

One request returns PNG, JPEG, WebP, or PDF. The parameter set covers full-page capture with lazy-image loading, CSS-selector element shots, dark mode, device presets or custom viewports, retina scale, PDF paper/margins/landscape/page ranges, custom CSS and JavaScript, clicks, hide selectors, selector/delay/network-idle waits, request blocking, headers/cookies/user agent/Authorization, timezone/geolocation, transparent backgrounds, resizing, TTL caching, signed public image links, async jobs with signed webhooks, bulk capture of up to 100 URLs, usage data, and an OpenAPI spec. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—work with Claude, Cursor, and other MCP clients.
See the ScreenshotNeo API docs for the complete option list.
# cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
# Python
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)
// Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The Free plan includes 1,000 shots each month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to try the API.
12. Migration checklist
- Record current URLs, viewport sizes, output formats, cookies, headers, and acceptable load times.
- Capture representative pages, including HTTPS, login-protected pages, pages with consent banners, lazy images, and deliberate failures.
- Map PhantomJS callbacks to explicit outcomes: success, failed load, resource timeout, page error, and total deadline.
- Compare output dimensions, fonts, dynamic content timing, and failure handling in the replacement.
- Run both systems in parallel, then remove the legacy process only after your error and cost budgets are understood.
FAQ
Does increasing resourceTimeout always fix a hang?
No. It limits one resource at a time and must be set before the initial open. It does not bound total process time or stop page JavaScript.
Why does page.open report success while the screenshot is incomplete?
Load completion does not mean an application has finished rendering lazy or asynchronous content. Add bounded waits, console/error logging, and a render condition specific to the page.
Should I keep patching PhantomJS?
Use the diagnostics for a legacy job you must stabilize, but plan migration because the upstream project is archived, suspended, and unmaintained.
Can a web request safely launch PhantomJS directly?
It can, but a worker queue, child-process deadline, concurrency cap, and recorded exit status are safer than holding an HTTP connection open without a bound.


