ScreenshotNeo

BlogHow-to

How to Fix PhantomJS Command-Line Errors

Fix PhantomJS errors systematically: verify the binary, CLI syntax, script exit paths, JavaScript exceptions, page loading, TLS and X-server issues.

By the ScreenshotNeo team30 September 20267 min read

How to Fix PhantomJS Command-Line Errors

Start with the failure layer. Run phantomjs --version, confirm which executable your shell resolves, and then test a minimal script that calls phantom.exit(). After that, expose JavaScript exceptions with page.onError, log the result of page.open, and investigate network, TLS, proxy or legacy X-server conditions. PhantomJS documentation covers version 2.1.1 and is legacy material, so treat operating-system, package-manager and SSL compatibility as environment-specific.

1. Identify the exact error layer

Classify the symptom before changing flags. Each layer has a different fix:

Debug PhantomJS from the executable layer through script execution and page navigation.
Debug PhantomJS from the executable layer through script execution and page navigation.
Layer Typical symptom First check
Executable and PATH phantomjs: command not found, wrong version command -v phantomjs and phantomjs --version
CLI parsing Usage output, script never starts Command order and script path
Script lifecycle Process hangs Every asynchronous path reaches phantom.exit()
JavaScript runtime Blank result or early termination page.onError and debug output
Navigation and network page.open returns fail Protocol, URL, resource logs and TLS
Platform environment X-server, proxy or permission errors Version, proxy settings and executable permissions

2. Verify the executable and version

The documented command form is phantomjs [options] somescript.js [args]. Check both the resolved binary and its version:

command -v phantomjs
which -a phantomjs
phantomjs --version
phantomjs --help

Multiple installations can conflict. Remove stale package-manager copies from PATH, or invoke the intended binary by absolute path. --help and --version stop immediately; they do not execute a script placed after them. See the PhantomJS command-line reference and official troubleshooting guide.

Installation and wrapper errors

If a Node or npm wrapper reports spawn ENOENT, EPERM, permission denied, ECONNRESET or ETIMEDOUT, separate that from a PhantomJS JavaScript exception. These messages usually indicate a missing executable, write or cache permissions, antivirus interference, or a download/network failure during installation. Inspect the wrapper’s resolved binary and npm cache permissions before debugging page code. The npm package guidance is secondary and dated; verify it against your current environment.

3. Prove that the CLI and script lifecycle work

Create hello.js:

console.log('PhantomJS started');
phantom.exit();

Run it with the documented syntax:

phantomjs hello.js

If this process does not terminate, your script is missing a termination path. The quick start explicitly warns that PhantomJS will not terminate until phantom.exit() is called. Put the exit call inside success, failure and timeout callbacks as appropriate, and ensure it runs only after asynchronous work is complete.

Arguments and ordering

phantomjs --debug=true capture.js https://example.com

Read positional arguments with system.args:

var system = require('system');
var url = system.args[1] || 'https://example.com';
console.log('URL:', url);
phantom.exit();

4. Surface hidden JavaScript exceptions

Add an error handler before opening the page. It prints the exception and each stack frame:

var page = require('webpage').create();

page.onError = function (message, trace) {
  console.error('Page error:', message);
  trace.forEach(function (frame) {
    console.error('  ', frame.file, 'line', frame.line, frame.function || 'anonymous');
  });
};

page.open('https://example.com', function (status) {
  console.log('Open status:', status);
  phantom.exit(status === 'success' ? 0 : 1);
});

Use --debug=true for additional warnings:

phantomjs --debug=true capture.js

For deeper inspection, the CLI supports --remote-debugger-port=9000 and --remote-debugger-autorun=yes. Keep remote debugging bound to a protected environment; it is an inspection tool, not a production fix.

5. Diagnose page navigation failures

A running PhantomJS process can still fail to load a page. The page.open callback reports success or fail:

A failed page.open call points to navigation, network, TLS or proxy behavior rather than necessarily to the CLI.
A failed page.open call points to navigation, network, TLS or proxy behavior rather than necessarily to the CLI.
var page = require('webpage').create();
var system = require('system');
var url = system.args[1] || 'https://example.com';

page.onError = function (message, trace) {
  console.error(message);
  trace.forEach(function (frame) {
    console.error(frame.file + ':' + frame.line);
  });
};

page.open(url, function (status) {
  console.log('page.open:', status, url);
  if (status === 'success') {
    console.log(page.title);
  }
  phantom.exit(status === 'success' ? 0 : 1);
});

Always include http:// or https://. A missing protocol, inaccessible host, authentication barrier, failed resource or TLS problem can produce fail without indicating a CLI parsing error. The page.open API documents the callback status.

Log resource requests

page.onResourceRequested = function (request) {
  console.log('REQUEST', request.method, request.url);
};
page.onResourceReceived = function (response) {
  console.log('RESPONSE', response.status, response.url);
};

Use these hooks to find a host, redirect or asset that stalls navigation. Avoid logging credentials or sensitive headers.

6. HTTPS, SSL and proxy problems

If HTTP succeeds while HTTPS fails, inspect the SSL/OpenSSL libraries used by the selected PhantomJS binary and verify the certificate chain in that environment. Do not treat --ignore-ssl-errors=true as a general repair: it suppresses certificate errors while leaving trust and compatibility problems unresolved.

On Windows, the troubleshooting documentation describes --proxy-type=none as a workaround for major latency caused by the default proxy setting. Use it only when that symptom and environment match:

phantomjs --proxy-type=none capture.js

7. Configure settings before page.open

WebPage settings such as resourceTimeout must be assigned before the initial navigation. Changing them after page.open has started does not affect that call:

var page = require('webpage').create();
page.settings.resourceTimeout = 15000;
page.settings.userAgent = 'Mozilla/5.0 PhantomJS';
page.open('https://example.com', function (status) {
  console.log(status);
  phantom.exit();
});

See the WebPage settings reference. A timeout should lead to a logged failure and an exit path; otherwise a script may appear hung.

8. Resolve “cannot connect to X server”

This message is version-specific. The official FAQ says PhantomJS 1.4 and earlier required an X server, while 1.5 and later were pure headless and did not require X11 or Xvfb. First check phantomjs --version and the actual binary path. Do not add Xvfb automatically when a newer binary is running. Read the official FAQ for the documented historical behavior.

9. A complete diagnostic script

var system = require('system');
var webpage = require('webpage');

var url = system.args[1];
if (!url) {
  console.error('Usage: phantomjs diagnose.js https://example.com');
  phantom.exit(2);
}

var page = webpage.create();
page.settings.resourceTimeout = 20000;

page.onError = function (message, trace) {
  console.error('[page error]', message);
  trace.forEach(function (frame) {
    console.error(' ', frame.file + ':' + frame.line, frame.function || '');
  });
};
page.onResourceRequested = function (request) {
  console.log('[request]', request.method, request.url);
};
page.onResourceReceived = function (response) {
  console.log('[response]', response.status, response.url);
};

page.open(url, function (status) {
  console.log('[open]', status);
  if (status === 'success') {
    console.log('[title]', page.title);
    console.log('[content bytes]', page.content.length);
  }
  phantom.exit(status === 'success' ? 0 : 1);
});
phantomjs --debug=true diagnose.js https://example.com

10. Troubleshooting checklist

  • Run command -v phantomjs, which -a phantomjs and phantomjs --version.
  • Run a two-line script that logs and calls phantom.exit().
  • Confirm the command is phantomjs [options] script.js [args].
  • Remember that --help and --version stop without running scripts.
  • Add page.onError before navigation.
  • Log page.open‘s status and include the URL protocol.
  • Log resource requests when a host or asset may be blocking the load.
  • Set resourceTimeout and related settings before page.open.
  • For HTTPS-only failures, inspect SSL/OpenSSL setup.
  • Use --proxy-type=none only for the documented Windows proxy-latency case.
  • Check the version before responding to an X-server error.

11. Performance, reliability and cost considerations

PhantomJS is a legacy browser. Keep diagnostic runs small, set a resource timeout, and exit deterministically so failed jobs do not consume worker slots indefinitely. Cache or reuse inputs at your orchestration layer when the same page is requested repeatedly. Capture request and response logs only during diagnosis because verbose output adds I/O and may expose URLs.

There is no universal current compatibility guarantee in the archived documentation. Pin the executable used by a job, record its version, and validate it against the operating system, certificate store and target sites you depend on. For production workloads, distinguish a CLI launch failure from a page-load failure in monitoring so retries target the correct layer.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. One request returns a PNG, JPEG, WebP or PDF, without maintaining a PhantomJS installation.

cURL (see the ScreenshotNeo API docs):

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}`);

Before capture, ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads 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 for Claude, Cursor and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

FAQ

Why does PhantomJS print help instead of running my script?

Check argument order. --help and --version terminate immediately, so place normal options and the script command correctly.

Why does a script hang after page.open?

An asynchronous branch probably never calls phantom.exit(). Add success, failure and timeout exits and log the callback status.

Is an X server required?

Only according to the documented historical behavior of PhantomJS 1.4 and earlier. Verify the binary version before adding X11 or Xvfb.

Should I ignore SSL errors?

No as a blanket fix. Inspect the SSL/OpenSSL installation and certificate chain first; ignoring errors hides the trust problem.

What does spawn ENOENT mean?

In an npm wrapper, it generally means the child executable cannot be found. Check installation, PATH and the wrapper’s configured binary separately from page JavaScript.