Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use CasperJS’s underlying PhantomJS WebPage object: call this.page.addCookie(cookie) inside a navigation callback, then check the Boolean it returns. The cookie’s domain must match the page currently loaded, or PhantomJS can reject it.

This is a legacy workflow. The CasperJS project states that it is no longer actively maintained, and PhantomJS’s cookie API does not guarantee compatibility with a particular modern site or authentication flow.

The direct method: this.page.addCookie()

CasperJS exposes its PhantomJS page through this.page. Add the cookie after CasperJS has opened a page on the target host and before performing the action that depends on the cookie.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var casper = require('casper').create();

casper.start('https://example.com/', function () {
    var added = this.page.addCookie({
        name: 'session',
        value: 'abc123',
        domain: 'example.com',
        path: '/',
        secure: true,
        httponly: true
    });

    this.echo('Cookie added: ' + added);
});

casper.run();

Replace the host, cookie name, value, and attributes with those required by the site. PhantomJS documents addCookie(Cookie) as returning true when the cookie is accepted and false otherwise. Always capture that result instead of assuming the cookie was stored.

The callback runs while the target page is available as CasperJS’s current page. Using a matching domain and a path that covers the URL where the cookie is needed avoids the most common rejection.

A complete navigation-and-check example

This example opens a host, adds the cookie, checks the return value, and then inspects the cookies visible to the current URL.

var casper = require('casper').create();
var target = 'https://example.com/';

casper.start(target, function () {
    var ok = this.page.addCookie({
        name: 'session',
        value: 'abc123',
        domain: 'example.com',
        path: '/',
        secure: true,
        httponly: true
    });

    this.echo('addCookie returned: ' + ok);
    if (!ok) {
        this.echo('Cookie was not accepted; check the domain, path, and attributes.');
    }
});

casper.then(function () {
    var visible = this.page.cookies;
    this.echo('Cookies visible to ' + this.getCurrentUrl() + ':');
    this.echo(JSON.stringify(visible, null, 2));
});

casper.run();

Run it with the CasperJS executable used by your installation. The second step reads page.cookies, an array of cookies visible to the current URL. It is an inspection mechanism; PhantomJS recommends page.addCookie for setting cookies.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cookie fields and how to choose them

Field Use Practical check
name The cookie name. It is required.
value The value sent with that name. It is required; use the exact value expected by the site.
domain The host scope for the cookie. It must be appropriate to the page currently loaded. A mismatch can make PhantomJS reject the cookie.
path The URL path scope. Use a path that includes the route your next action will visit; / covers the site root and its descendants.
secure Marks the cookie as secure. Set it only when that matches the target site’s cookie requirements and connection.
httponly Marks the cookie as HttpOnly. Use the WebPage API when this attribute is needed.
expires or expiry An optional expiration value documented by PhantomJS. Use the format expected by the PhantomJS version installed in your environment.

The documented cookie object includes name, value, domain, path, httponly, secure, and optionally an expiration field. Start with only the attributes the target requires, then add the others deliberately.

Adding a cookie before the action that needs it

  1. Open a URL on the target host. This gives PhantomJS a current page whose domain can be checked.
  2. Call this.page.addCookie() in the navigation callback. Supply the name, value, matching domain, and suitable path.
  3. Check the Boolean result. Log or branch on false so a rejected cookie cannot silently invalidate the rest of the run.
  4. Continue with the site action. Navigate, submit a form, or load the route that relies on the cookie.
  5. Inspect this.page.cookies when diagnosing behavior. The property shows cookies visible to the current URL.

If the cookie is needed on another host, repeat the process with a page and domain appropriate to that host. Do not treat a cookie accepted for one host as proof that it will be visible everywhere.

HttpOnly cookies: why evaluate() is different

casper.evaluate() executes JavaScript in the remote page’s DOM context, like code entered in that page’s browser console. That is distinct from PhantomJS’s WebPage cookie API.

Page JavaScript cannot create an HttpOnly cookie. If the cookie must carry the httponly attribute, set it with this.page.addCookie() and provide the attribute in the cookie object. Use evaluate() only for page-context work that does not require an HttpOnly cookie.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why addCookie() returns false

Domain does not match the current page

This is the primary documented rejection case. Open a URL on the intended host first and make the cookie’s domain correspond to that host. Check for spelling differences and accidental use of a different subdomain.

Path does not cover the route

A cookie can be present yet unavailable on the URL your next step visits if its path is too narrow. Use / when the cookie is intended for the whole site, or choose the specific path required by the application.

Attributes do not match the site

Review secure, httponly, and expiration settings against the target’s requirements. Remove optional attributes temporarily to identify which field causes rejection, then restore the required value.

The script checks the wrong page

page.cookies reports cookies visible to the current URL. Inspect it after navigation has settled on the host and route where the cookie should be used, not only on an unrelated page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The cookie value is not valid for the application

A Boolean true means PhantomJS accepted the cookie object; it does not establish that the site will authenticate the value. Confirm that the name, value, scope, and lifetime are the ones issued or expected by the application.

Compatibility and maintenance limits

The CasperJS repository explicitly says, “CasperJS is no longer actively maintained.” Its documentation is labeled 1.1.0-DEV, and the PhantomJS cookie pages describe a legacy API. Check the CasperJS and PhantomJS versions installed on the machine before diagnosing a difference between environments.

Neither the CasperJS project page nor the PhantomJS API page promises that a specific modern site, login flow, bot check, or JavaScript application will accept a cookie set this way. Validate the complete flow against the actual target. If the site changes its authentication mechanism, a correctly formed cookie object may still be insufficient.

Reliability and operational checklist

  • Open the target host before calling addCookie().
  • Use the exact cookie name and value required by the application.
  • Choose a domain and path that cover the URL used next.
  • Set secure and httponly deliberately rather than copying them blindly.
  • Log the Boolean return value on every run.
  • Inspect this.page.cookies when the site behaves as if the cookie is missing.
  • Record the CasperJS and PhantomJS versions with your script, because this is an unmaintained stack.
  • Do not infer site authentication success solely from PhantomJS accepting the cookie object.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If the outcome you need is a website screenshot rather than a CasperJS browser session, ScreenshotNeo is the first screenshot API to try: it removes consent banners, popups and chat widgets before capture, bills only clean shots, and its lowest paid plan starts at $5.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a one-call capture, see the ScreenshotNeo API documentation:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo can accept custom cookies and headers when a capture needs a particular request context. It also supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, device presets or custom viewports, retina scale, PDF output, custom CSS and JavaScript, pre-capture clicks, selector or network-idle waits, request and resource blocking, user-agent, timezone and geolocation settings, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API and an OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs.

Each response identifies its result with X-Page-Verdict and X-Billed headers. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing. An MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.

Plan Included screenshots Price
Free 1,000 per month $0, no card
Starter 3,000 $5
Growth 15,000 $15
Pro 60,000 $39
Scale 250,000 $99
Business 1,000,000 $249

Yearly billing gives two months free, and every feature is available on every plan. Start with 1,000 free screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Where is the cookie list exposed in CasperJS?

Use the underlying PhantomJS property this.page.cookies; it returns the cookies visible to the current URL.

Can page JavaScript create an HttpOnly cookie?

No. Use this.page.addCookie() and set httponly: true in the cookie object.

Is CasperJS suitable for new automation projects?

Treat it as legacy: the official project states that CasperJS is no longer actively maintained, so validate the installed versions and target site carefully.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.