How to Stop PhantomJS When page.open Hangs
Stop PhantomJS page.open hangs with a per-resource timeout, independent watchdog, diagnostics, and a guaranteed phantom.exit path.

When page.open() appears to hang, use two different controls: a per-resource timeout for diagnosing stalled requests and an independent watchdog for the entire page-load operation. When the watchdog expires, log the deadline, call page.stop(), and then call phantom.exit(1) without waiting for another callback.
page.open(url, callback) is callback and event driven. Its callback is delivered through page.onLoadFinished with a status of success or fail. PhantomJS will keep running until execution reaches phantom.exit(), so a normal callback path and a timeout path must both terminate the process.
Use an independent watchdog around page.open
This complete example bounds the whole operation while also reporting individual resource timeouts. The 30-second and 10-second values are examples; choose limits for your URL, network and runtime.
var page = require('webpage').create();
var finished = false;
var watchdogMs = 30000; // Overall page-load deadline.
// Configure this before the initial page.open call.
page.settings.resourceTimeout = 10000; // Per-resource limit, in milliseconds.
page.onResourceTimeout = function (request) {
console.log('Resource timeout: ' + request.url +
' (' + request.errorCode + ': ' + request.errorString + ')');
};
var watchdog = setTimeout(function () {
if (finished) {
return;
}
finished = true;
console.log('Overall page load deadline exceeded');
page.stop();
phantom.exit(1);
}, watchdogMs);
page.open('https://example.com', function (status) {
if (finished) {
return;
}
finished = true;
clearTimeout(watchdog);
console.log('Page load status: ' + status);
phantom.exit(status === 'success' ? 0 : 1);
});
Run it with:
phantomjs capture.js
The finished flag makes completion idempotent. If the page callback arrives just as the timer fires, only the first path performs cleanup and exits.
What each PhantomJS API actually guarantees
page.open() and the completion callback
The page.open API starts navigation. Its optional callback receives the page status after loading finishes, through the onLoadFinished event. The documented statuses are success and fail. A fail status indicates network errors according to the load-finished handler documentation.

Attach the callback as the second argument, or attach page.onLoadFinished before opening the URL. Do not put your only cleanup action in code that assumes a callback must eventually arrive; the independent watchdog is the escape hatch when completion never occurs.
page.settings.resourceTimeout
resourceTimeout is a millisecond limit for an individual resource request. Set it before the initial page.open(). When a resource reaches that limit, PhantomJS stops trying that resource, calls onResourceTimeout, and can continue with other parts of the page. The page.settings reference does not define this setting as a deadline for the complete page load.
page.onResourceTimeout
The onResourceTimeout handler receives request metadata, including the URL, request time, error code and error text. Log these fields to identify a slow third-party script, image, stylesheet, API call or other dependency.
page.stop()
page.stop() requests that page loading stop. Its official reference lists the method but does not promise that stopping causes the pending page.open callback to run. Treat it as best effort and keep process termination independent.
phantom.exit()
phantom.exit(returnValue) ends the PhantomJS process with the supplied exit code. The Quick Start guide warns that PhantomJS will not terminate unless execution reaches an exit call. Use code 0 for a successful load and a nonzero code for a failed load or watchdog expiration.
Choose timeout values without hiding real failures
| Control | Scope | What it tells you | What it does not do |
|---|---|---|---|
resourceTimeout |
One network resource | Identifies a request that exceeded its limit | Guarantee that the page or process exits |
| Watchdog timer | The complete script operation | Shows that your overall deadline was exceeded | Identify the exact root cause by itself |
page.stop() |
Current page loading | Requests that navigation stop | Guarantee a completion callback |
phantom.exit() |
PhantomJS process | Guarantees an explicit exit path | Make a failed page load successful |
Use a resource limit that allows normal assets to finish, then choose an overall watchdog that covers DNS, TLS negotiation, HTML, scripts and the slowest expected dependencies. Keep the values configurable through your deployment settings rather than scattering constants through several scripts.
Diagnostics that distinguish a slow resource from a stuck flow
- Log navigation start and deadline. Print the URL, start timestamp and configured watchdog duration before calling
page.open. - Log every resource timeout. Include
request.url,request.errorCode,request.errorStringandrequest.timewhen available. - Log completion status. The callback should print
successorfailbefore exiting. - Log watchdog expiry separately. A message such as
Overall page load deadline exceededmeans the script-level deadline fired; it does not prove which subsystem stalled. - Record the exit code. Supervisors, CI jobs and shell scripts can distinguish a successful capture (
0) from a failed load or timeout (1).
If the watchdog fires without an onResourceTimeout event, the available evidence does not establish a particular cause. Investigate the PhantomJS version, DNS and TLS, proxy configuration, network reachability, redirects, JavaScript navigation and the URL in the same environment where the hang occurs.
Common failure modes and fixes
The callback never runs
Cause: The load remains pending, or cleanup depends entirely on a callback that never arrives. Fix: Add the independent watchdog shown above. On expiry, call page.stop() and immediately call phantom.exit(1).
resourceTimeout is set but nothing exits
Cause: The setting is per request, not a complete operation deadline. A page can have other pending work, timers or navigation activity after one resource times out. Fix: Keep onResourceTimeout for diagnostics and add the overall watchdog for termination.
The resource handler is silent
Cause: The hang may not be a resource that crossed your configured limit, or the setting may have been applied after navigation began. Fix: Set page.settings.resourceTimeout and page.onResourceTimeout before page.open. If no event appears before the watchdog, inspect runtime, DNS, TLS, proxy and script behavior.
The process remains alive after a successful load
Cause: The callback logs a status but never calls phantom.exit(), or another timer keeps the event loop active. Fix: Clear the watchdog and exit from the callback. The Quick Start documentation specifically requires an exit call.
The process exits twice
Cause: The watchdog and callback race, or multiple handlers perform cleanup. Fix: Guard both paths with one shared finished flag and clear the timer in the callback.
Stopping causes missing output
Cause: page.stop() can interrupt loading before the page reaches the state your capture code expects, and its documentation does not guarantee a callback. Fix: Treat watchdog termination as a failed operation, write diagnostic logs before exiting, and retry only when your caller can safely repeat the request.
Navigation, scripts and retry edge cases
A page can begin a second navigation from JavaScript after the initial document arrives. The load-finished event describes the navigation lifecycle, not necessarily the readiness of an application-specific state. If your script waits for a selector or performs clicks, include that work inside the same outer deadline and make every asynchronous branch call a single success or failure function.
Retries should be bounded. A practical policy is one initial attempt, one retry for transient network failures, and a final nonzero exit. Do not blindly retry authentication failures, invalid URLs or deterministic script errors. Include the URL and attempt number in logs so a supervisor can identify repeated failures.
When PhantomJS runs under a shell, CI system or job queue, let the process exit code carry the result. A parent process can add a second external timeout, but the in-script watchdog still matters because it can log the page URL, timed-out resources and the exact point at which page.stop() was requested.
Performance, reliability and cost considerations
- Performance: A shorter resource timeout can reduce waiting on dead third-party hosts, but may omit legitimate slow assets. A shorter overall watchdog improves queue throughput while increasing false failures on slow pages.
- Reliability: Keep timeout and exit logic independent from page callbacks. This protects batch jobs from one navigation that never reports completion.
- Observability: Emit structured logs containing URL, start time, resource URL, error details, status and exit code. Preserve them with the job record.
- Compatibility: These APIs come from legacy PhantomJS documentation. Validate behavior against the PhantomJS version and operating system you maintain; the references do not establish compatibility with every release.
- Cost: PhantomJS itself does not provide a hosted capture billing model in this workflow. Your costs are the runtime, network and operations required to run and monitor it.
Or skip the browser setup
If your goal is a dependable screenshot rather than maintaining a PhantomJS process, ScreenshotNeo provides a GET-based website screenshot API. Its capture pipeline accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before the shot; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and each response reports the result in X-Page-Verdict and X-Billed headers.
See the ScreenshotNeo API documentation for parameters and response details. A direct request is enough:
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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const body = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', body);
ScreenshotNeo also supports full-page captures with lazy images loaded, element screenshots by CSS selector, dark mode, device presets, arbitrary viewports, retina scale, PDF output, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API and an OpenAPI specification. An MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.
There are 1,000 free screenshots each month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan. Create a free ScreenshotNeo account to try the API.
Short FAQ
Does resourceTimeout stop page.open?
No. It bounds an individual resource and invokes onResourceTimeout. Use a separate watchdog to bound the entire script.

Should I call phantom.exit() inside onResourceTimeout?
Usually no. One timed-out asset may not prevent the page from completing. Let the page continue while the overall watchdog decides whether the operation has exceeded its deadline.
Can I rely on page.stop() to invoke the callback?
No guarantee is documented. Call phantom.exit() independently after stopping.
What does a fail status prove?
The handler documentation associates fail with network errors. It does not identify which network condition caused the failure; use resource logs and environment diagnostics.
What if a page needs more than 30 seconds?
Increase the watchdog for that workload and keep a separate resource timeout. The example values are illustrative, not PhantomJS defaults.


