Recommended Free Tools
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
For a typical logged-in website, pass the session cookie to PhantomJS. If login and later page visits happen in the same PhantomJS process, its cookie jar normally carries the session forward automatically. Across separate runs, start PhantomJS with --cookies-file or save the cookie objects and restore them with phantom.addCookie before opening the protected page. Make sure each cookie’s domain and path apply to the URL you are opening.
These instructions are primarily for maintaining legacy PhantomJS automation: Selenium removed PhantomJS support in its 3.8.0 changelog and recommends headless Firefox or Chrome instead.
What “current session information” means
In the usual login flow, the website sends the browser a session cookie after authentication. The browser includes that cookie on later requests to matching pages, allowing the server to associate those requests with the logged-in session. In PhantomJS, that cookie lives in its cookie jar.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Passing cookies is not the same as exporting a complete browser profile. A site may also rely on local storage, a CSRF token, device binding, or other site-specific state. PhantomJS’s cookie APIs cover cookies; they do not automatically transfer every form of browser storage or every condition the website uses to recognize a user.
#1 Best Overall
- Same process: log in and open the protected page using the same PhantomJS process; the global cookie jar is retained.
- Separate processes: persist cookies in a cookie file or serialize and restore the cookie objects.
- Selenium: visit the target domain before adding cookies for it.
Keep the session in one PhantomJS process
If your script logs in and then navigates to a protected page without exiting, you usually do not need to copy cookies manually. PhantomJS documentation describes cookies in the global jar as being supplied when opening pertinent WebPages.
var page = require('webpage').create();
page.open('https://example.com/login', function (status) {
if (status !== 'success') {
console.log('Could not open login page');
phantom.exit(1);
return;
}
// Perform the site's login flow here. For example, use page.evaluate()
// to fill and submit the form, then wait for the result.
page.open('https://example.com/private', function (privateStatus) {
if (privateStatus !== 'success') {
console.log('Could not open protected page');
phantom.exit(1);
return;
}
// Inspect the page or perform the required work here.
console.log(page.url);
phantom.exit();
});
});
The example leaves the login interaction site-specific: form names, authentication redirects, and any required second factor vary by site. Do not open the protected URL until the login flow has actually completed and the session cookie has been issued. In production, check the resulting URL or page content to distinguish a successful login from a redirect back to the login form.
Persist cookies between PhantomJS runs
Use the built-in cookie file
Start PhantomJS with the cookie-file option:
phantomjs --cookies-file=/path/to/cookies.txt script.js
PhantomJS pre-populates its cookie array from cookie data in the startup file. The file lets a later process reuse cookies written by an earlier process, rather than relying on the lifetime of an in-memory jar. Keep the path stable and writable for the account running PhantomJS, and protect the file as you would any credential-bearing session data.
A cookie file is a cache of authentication state, not proof that the session remains valid. The server can expire or revoke a session even when the file still exists. On startup, open a lightweight authenticated-check URL and verify the result before doing work that assumes a logged-in user.
Rank #2
Save and restore cookie objects explicitly
Explicit serialization is useful when you need to control the transfer or the cookie-file approach does not fit your workflow. Save the jar after successful authentication, then restore it before opening the protected page in a later process:
var fs = require('fs');
var webpage = require('webpage');
var jarPath = '/tmp/phantom-session.json';
// In the process that has completed login:
fs.write(jarPath, JSON.stringify(phantom.cookies), 'w');
// In the later process, restore before page.open():
var page = webpage.create();
if (fs.isFile(jarPath)) {
var savedCookies = JSON.parse(fs.read(jarPath));
savedCookies.forEach(function (cookie) {
if (!phantom.addCookie(cookie)) {
console.log('Could not restore cookie: ' + cookie.name);
}
});
}
page.open('https://example.com/private', function (status) {
if (status !== 'success') {
console.log('Could not open protected page');
phantom.exit(1);
return;
}
// Confirm authentication before continuing.
console.log('Opened: ' + page.url);
phantom.exit();
});
This illustrates the two sides of the transfer, but they belong in separate executions in a real cross-run workflow: run the save operation after login in the first process, and the restore operation at startup in the next. The cookie object fields documented for this API include name, value, domain, and optional path, httponly, secure, and expires. Preserve the applicable attributes when copying or transforming cookies. phantom.addCookie returns a Boolean indicating whether the cookie was added.
Use cookies with Selenium-controlled PhantomJS
When Selenium controls PhantomJS, add a cookie only after navigating the driver to a page on the cookie’s domain. PhantomJS rejects or ignores a page cookie whose domain does not match the current page. A typical sequence is to open the domain, add the cookie, and then load the protected route:
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problems// Python Selenium-style sequence; driver is a PhantomJS WebDriver instance.
driver.get('https://example.com/')
driver.add_cookie({
'name': 'session_id',
'value': 'SESSION_VALUE',
'domain': 'example.com',
'path': '/',
'secure': True,
'httpOnly': True
})
driver.get('https://example.com/private')
Use the actual cookie name, value, domain, and security attributes issued by the site. The example is illustrative; a secure cookie should be used over HTTPS, and cookie attributes must reflect the real cookie rather than being copied blindly from this sample.
Rank #3
Persist through the .NET PhantomJS driver service
A documented .NET Selenium pattern configures the service’s cookie-file path before constructing the driver:
DriverService service = PhantomJSDriverService.CreateDefaultService(driverpath);
service.CookiesFile = "path/to/cookies.txt";
IWebDriver driver = new PhantomJSDriver(service);
The cited Selenium example describes cookies being automatically saved to that file. Check the file’s permissions and verify the next run’s authentication rather than assuming saved cookies remain accepted by the site.
Cookie matching, expiration, and security
Domain and path must match
Check the cookie’s domain against the hostname in the destination URL and its path against the requested route. PhantomJS’s WebPage API states that a cookie is ignored or rejected if its domain does not match the current page. A cookie for example.com should not be assumed to apply to a different host such as accounts.example.com; inspect the site’s actual cookie scope.
Preserve flags and expiry
When explicitly transferring cookies, retain the relevant secure, httponly, and expires properties, as well as the name, value, domain, and path. Session cookies may not have a persistent expiry, and persistent cookies can still be invalidated server-side. Treat a successful cookie restore as a starting point for an authentication check, not as a guarantee of a valid session.
Protect stored session state
A session cookie can grant access as the account that created it. Store cookie files and JSON exports with restrictive filesystem permissions, avoid committing them to source control, and do not print cookie values to logs. Remove stored session data when it is no longer needed. These are operational precautions for any saved authentication credential.
Troubleshoot a session that is not accepted
- The protected page shows the login screen: check the final URL and page content for a redirect, and confirm the login completed before saving cookies. The site may have expired or revoked the session.
- A restored cookie has no effect: restore it before calling
page.open()for the protected URL. Check exact host and path matching; cookies are not automatically valid for every subdomain or route. phantom.addCookiereturns false: inspect the cookie fields, especially its domain, and make sure it is appropriate for the current page context. Preserve the documented cookie attributes rather than passing a partial or malformed object.- It works in one run but not the next: verify PhantomJS starts with the intended
--cookies-filepath, that the process can read and write it, and that the server still accepts the session. - It works in PhantomJS but not in a Selenium cookie injection: navigate the driver to the matching domain before adding the cookie, then load the protected route.
- Cookies appear correct but authentication still fails: the site may require local storage, a CSRF token, device binding, or another site-specific mechanism. Cookie transfer alone cannot reproduce every browser state.
Plan for PhantomJS’s legacy status
Selenium’s 3.8.0 changelog records that support for PhantomJS was dropped and recommends headless Firefox or Chrome instead. That makes these techniques most appropriate for maintaining an existing PhantomJS workflow. For a new automation project, choose a currently maintained browser integration and verify its current support and cookie APIs in that project’s documentation; the PhantomJS-specific commands here should not be assumed to transfer unchanged.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server, not a way to authenticate to a private site or transfer a PhantomJS session. For pages you can access without that session, a single request can return an image or PDF. See the ScreenshotNeo API documentation.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
ScreenshotNeo removes cookie/consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots.
Sign up for 1,000 free screenshots a month—no card required.
Frequently Asked Questions
Does a PhantomJS cookie file contain a complete browser profile?
No. It stores cookie state, not every browser setting or storage mechanism a site may use.
Can a session cookie be reused forever if it is saved?
No. Expiration or server-side revocation can invalidate a saved cookie; verify authentication when the process starts.
Free tools Windows power users keep installed
One-click scans. No signup required.
Can ScreenshotNeo reuse a PhantomJS login session?
No. It is a screenshot service and does not transfer PhantomJS cookies or authenticate to a private page.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

