ScreenshotNeo

BlogHow-to

How to Pass Current Session Information to PhantomJS

Learn how to reuse PhantomJS login sessions with cookies, persist them between runs, transfer Selenium cookies, and diagnose authentication failures.

By the ScreenshotNeo team30 September 20268 min read

How to Pass Current Session Information to PhantomJS

Direct answer: pass the current session to PhantomJS as cookies. If login and protected-page capture happen in one PhantomJS process, the global cookie jar is reused automatically. To survive a process restart, start PhantomJS with --cookies-file=/path/to/cookies.txt, or serialize phantom.cookies to JSON and restore each cookie with phantom.addCookie() before opening the protected URL. The cookie domain and path must match the page you open.

This guide covers same-process reuse, cross-process persistence, explicit JSON transfer, Selenium-controlled PhantomJS, cookie expiry, domain rules, local-storage limitations, security, troubleshooting, and migration considerations. PhantomJS is legacy software; Selenium removed official PhantomJS support in version 3.8.0 and recommends maintained headless Firefox or Chrome for new automation.

1. Reuse a session in the same PhantomJS process

PhantomJS keeps cookies in a global cookie jar. Cookies supplied by the server during login are sent automatically when you open another pertinent page in the same process. You do not need to copy the cookie manually.

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

page.open('https://example.com/login', function (status) {
  if (status !== 'success') {
    console.log('Login page failed: ' + status);
    phantom.exit(1);
    return;
  }

  page.evaluate(function () {
    document.querySelector('input[name="username"]').value = 'alice';
    document.querySelector('input[name="password"]').value = 'correct-horse-battery-staple';
    document.querySelector('form').submit();
  });

  window.setTimeout(function () {
    page.open('https://example.com/private', function (privateStatus) {
      console.log('Protected page: ' + privateStatus);
      console.log('Final URL: ' + page.url);
      page.render('/tmp/private.png');
      phantom.exit(privateStatus === 'success' ? 0 : 1);
    });
  }, 1500);
});

Use a site-specific post-login check instead of assuming that a successful HTTP load means authentication succeeded. Check the final URL, page title, or a selector that only appears for signed-in users. Some applications redirect unauthenticated visitors back to /login while still returning a technically successful page load.

2. Persist cookies between PhantomJS runs

When the login and capture happen in separate processes, use PhantomJS’s cookie file option:

A cookie jar can persist a PhantomJS session between process runs.
A cookie jar can persist a PhantomJS session between process runs.
phantomjs --cookies-file=/path/to/cookies.txt session-capture.js

The cookie file is loaded when PhantomJS starts and updated as the process runs. The official phantom.cookies documentation describes the global jar and its startup cookie data. A cookie file stores cookie state, not a complete browser profile, so it does not automatically include local storage, IndexedDB, service-worker state, cached resources, or browser preferences.

First-run and later-run flow

  1. Start PhantomJS with the same writable cookie-file path.
  2. Open the login page and submit credentials on the first run.
  3. Wait for the login redirect or authenticated selector.
  4. Open the protected URL and let PhantomJS write the updated jar.
  5. On later runs, open the protected URL and verify that it did not redirect to login.

Treat the file as a cache rather than permanent proof of authentication. Session cookies can expire, be revoked, or be invalidated by a server-side logout. Protect the file with filesystem permissions because possession of a valid session cookie can provide account access.

3. Serialize and restore cookies as JSON

Explicit JSON transfer gives you control over which cookies are saved, where they are stored, and how they are moved between workers. Save the documented cookie fields, including name, value, domain, optional path, httponly, secure, and expires.

var fs = require('fs');
var page = require('webpage').create();
var jarPath = '/tmp/phantom-session.json';

function restoreCookies() {
  if (!fs.isFile(jarPath)) {
    return;
  }

  var cookies = JSON.parse(fs.read(jarPath));
  cookies.forEach(function (cookie) {
    var accepted = phantom.addCookie(cookie);
    if (!accepted) {
      console.log('Cookie rejected: ' + cookie.name + ' for ' + cookie.domain);
    }
  });
}

function saveCookies() {
  fs.write(jarPath, JSON.stringify(phantom.cookies), 'w');
}

restoreCookies();
page.open('https://example.com/private', function (status) {
  if (status !== 'success' || /\/login(?:[/?#]|$)/.test(page.url)) {
    console.log('Session missing or expired: ' + page.url);
    phantom.exit(2);
    return;
  }

  saveCookies();
  page.render('/tmp/private.png');
  phantom.exit(0);
});

phantom.addCookie() returns a Boolean. A false result usually means the cookie is malformed or its domain does not match the current page context. The PhantomJS WebPage API documents the accepted cookie structure and rejection behavior.

  • A cookie for app.example.com is not automatically valid for admin.example.com.
  • A leading-dot domain such as .example.com can cover subdomains when the server sets it that way.
  • The cookie path must cover the request path. A cookie restricted to /account may not be sent to /reports.
  • secure: true cookies require an HTTPS page.
  • Preserve the expiration value. An expired cookie can be accepted into a jar but will not authenticate a request.

4. Passing cookies from Selenium-controlled PhantomJS

If another client performs the login, navigate the Selenium driver to the target domain before adding cookies. PhantomJS rejects a page cookie when its domain does not match the current page.

// C# Selenium example
DriverService service = PhantomJSDriverService.CreateDefaultService(driverPath);
service.CookiesFile = "path/to/cookies.txt";
IWebDriver driver = new PhantomJSDriver(service);

driver.Navigate().GoToUrl("https://example.com/");
driver.Manage().Cookies.AddCookie(
    new OpenQA.Selenium.Cookie("session_id", sessionValue, ".example.com", "/", DateTime.UtcNow.AddHours(2)));
driver.Navigate().GoToUrl("https://example.com/private");

For a driver-managed workflow, prefer the driver’s cookie API or a configured cookies file instead of editing PhantomJS internals. The Selenium changelog records that PhantomJS support was dropped; use this pattern mainly to maintain an existing legacy system.

5. Moving session cookies with cURL, Python, and Node.js

These examples are useful when a login service or another automation tool produces the cookie data that PhantomJS must consume.

curl -c /tmp/site.cookies -L -d 'username=alice&password=secret' https://example.com/login
curl -b /tmp/site.cookies -L https://example.com/private -o private.html

PhantomJS’s cookie-file format is not guaranteed to be interchangeable with every cURL version. If direct reuse fails, parse the cookie values and create documented PhantomJS cookie objects instead.

Python requests

import json
import requests

s = requests.Session()
s.post('https://example.com/login', data={'username': 'alice', 'password': 'secret'}, timeout=30)
with open('/tmp/phantom-session.json', 'w') as f:
    json.dump([{
        'name': c.name,
        'value': c.value,
        'domain': c.domain,
        'path': c.path,
        'secure': c.secure,
    } for c in s.cookies], f)

r = s.get('https://example.com/private', timeout=30)
r.raise_for_status()
print(r.url)
const fs = require('node:fs');

// Convert cookies returned by your login client to PhantomJS fields.
const phantomCookies = loginCookies.map(c => ({
  name: c.name,
  value: c.value,
  domain: c.domain || 'example.com',
  path: c.path || '/',
  secure: Boolean(c.secure),
  httponly: Boolean(c.httpOnly),
  ...(c.expires ? { expires: c.expires } : {})
}));

fs.writeFileSync('/tmp/phantom-session.json', JSON.stringify(phantomCookies));

Do not log cookie values, include them in bug reports, or commit cookie files to source control.

6. What cookies do not transfer

“Current session information” usually means a server-issued session ID cookie. Some sites also require local-storage tokens, CSRF values, device fingerprints, client certificates, or server-side binding to an IP address or user agent. Cookie transfer alone cannot reproduce those mechanisms.

Cookies transfer the usual session ID, but not every browser storage mechanism.
Cookies transfer the usual session ID, but not every browser storage mechanism.

If the application stores a bearer token in local storage, retrieve it through page JavaScript after login and restore it before navigation:

page.evaluate(function (token) {
  window.localStorage.setItem('access_token', token);
}, tokenFromYourSecureStore);

Only do this when the application documents that storage contract. A token copied from one browser context can be invalidated when the server detects a changed device or user agent.

7. Troubleshooting common failures

Symptom Likely cause Fix
Cookie is rejected by addCookie Domain does not match the current page, or required fields are missing. Open the matching domain first; preserve name, value, domain, path, secure, httponly, and expiry fields.
Protected page redirects to login Cookie expired, was revoked, or was restored after navigation. Restore before page.open, check expiry, and perform a fresh login when the authenticated selector is absent.
Works on HTTP but not HTTPS The cookie has the secure flag or the site enforces HTTPS. Use the HTTPS URL and keep secure: true.
Only some pages are authenticated Cookie path or subdomain scope is too narrow. Inspect the original Set-Cookie attributes and use the exact domain and path required by each host.
Cookie file is empty PhantomJS exited before the login response completed or could not write the path. Wait for the redirect, call phantom.exit only after saving, and verify directory permissions.
Login form submits but session is not set JavaScript login, CSRF token, or an additional API request was skipped. Wait for network activity to finish and reproduce the browser’s token and request sequence.
JSON restore succeeds but authentication fails The application also depends on local storage, user agent, or device binding. Restore those site-specific values or use a maintained browser with a persistent profile.

8. Reliability, performance, and security checklist

  • Validate every run: check the final URL and an authenticated-only selector before capturing data.
  • Use bounded waits: avoid infinite polling; fail clearly when login does not complete within a chosen deadline.
  • Keep one jar per account: concurrent jobs writing one cookie file can overwrite each other’s sessions.
  • Refresh deliberately: re-login when the session expires instead of retrying the same invalid cookie forever.
  • Reduce startup cost: reuse one PhantomJS process for multiple pages when isolation requirements allow it.
  • Protect secrets: restrict cookie-file permissions, encrypt backups, and remove temporary jars after a job.
  • Record safe diagnostics: log status, URL, and cookie names, never cookie values or passwords.
  • Expect legacy limits: modern sites may depend on browser APIs PhantomJS does not implement correctly.

9. Or skip the browser setup

If your goal is a clean screenshot rather than maintaining a logged-in PhantomJS browser, ScreenshotNeo provides a single GET request for a PNG, JPEG, WebP, or PDF. Its request options include custom cookies, headers, user agents, Authorization, waits, JavaScript, custom CSS, device presets, full-page capture, and element selectors. See the ScreenshotNeo documentation for the complete parameter list.

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

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are never billed, and response headers report the page verdict and billing result. An MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

10. FAQ

Restore it before navigation. Adding it afterward does not retroactively change the request that already happened; reload the page after a successful restore.

No. It contains cookie values, which can still grant access. Store it as a credential and protect it accordingly.

Why does a session work in Chrome but fail in PhantomJS?

The site may require local storage, modern browser APIs, a current TLS stack, or device-bound signals that PhantomJS does not provide.

Should new projects still use PhantomJS?

Usually no. Selenium removed PhantomJS support and recommends maintained headless Firefox or Chrome. Keep these techniques for legacy systems that cannot migrate immediately.