Free tools Windows power users keep installed

One-click scans. No signup required.

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

In CasperJS, add a cookie through the underlying PhantomJS page object: this.page.addCookie({...}). Call it while the page is on a URL whose domain matches the cookie, check the Boolean result, and then reload or continue to the action that needs the cookie. The method supports attributes such as path, secure, httponly, and expires.

The direct CasperJS solution

CasperJS exposes its PhantomJS WebPage instance as this.page. PhantomJS documents page.addCookie(cookie) as the supported way to set a cookie, and the method returns true when the cookie is accepted or false when it is rejected.

var casper = require('casper').create();

var target = 'https://example.com/';

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

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

// Open the URL again so the next request is made with the new cookie.
casper.thenOpen(target, function () {
    this.echo('Page opened after setting the cookie.');
});

casper.run();

Replace the host, cookie name, value, and attributes with the values required by the site. The domain must match the current page; a mismatch can cause PhantomJS to reject or ignore the cookie. The example first opens the target, sets the cookie, and opens the target again so a subsequent request can use it.

CasperJS’s project repository describes CasperJS as a navigation utility for PhantomJS and exposes the page object used above. See the CasperJS project and PhantomJS’s addCookie documentation.

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

How the cookie-setting sequence works

1. Create a CasperJS instance

Start with require('casper').create(). CasperJS callbacks run with the Casper instance as this, which is why the WebPage object is available as this.page.

2. Navigate to a matching host

Use casper.start() with the target URL. Adding a cookie while the page is associated with the target host avoids the domain-mismatch failure documented by PhantomJS. A cookie for example.com should not be added while the current page belongs to an unrelated host.

3. Add the cookie and capture the result

Pass an object to this.page.addCookie() and save its return value. Do not assume that the call succeeded merely because the script continued running.

4. Make the request that needs the cookie

If the cookie must be sent as an HTTP request cookie, open or reload the target after adding it. For a page-only cookie that is read by the current document, you can perform the page action in the same navigation callback, but reopening the URL is the clearer pattern for authentication or server-side state.

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

5. Verify the result on the target URL

PhantomJS exposes page.cookies, an array of cookies visible to the current URL. Inspect that property after setting the cookie and on the page where you expect it to be available.

casper.start('https://example.com/', function () {
    var added = this.page.addCookie({
        name: 'theme',
        value: 'dark',
        domain: 'example.com',
        path: '/'
    });

    this.echo('addCookie returned: ' + added);

    var visible = this.page.cookies;
    this.echo('Visible cookie count: ' + visible.length);

    for (var i = 0; i < visible.length; i++) {
        this.echo(visible[i].name + '=' + visible[i].value);
    }
});

casper.run();

page.cookies reports cookies visible to the current URL, not an unrestricted browser-wide store. Check it after navigation to the host and path you care about.

Cookie object fields to choose deliberately

PhantomJS documents a cookie object with a required name and value plus attributes that control where and how it applies. Use only the attributes needed by the target site.

Field What to provide Practical check
name The cookie name. Use the exact name expected by the application.
value The value, such as a session or preference token. Copy the value exactly; do not add surrounding quotes unless the site requires them.
domain The cookie’s host scope. It must be appropriate to the current page. A mismatch can make addCookie return false.
path The URL path scope, commonly / when the site expects the cookie throughout the host. Use a path that covers the request or page where you will verify the cookie.
secure A Boolean indicating the secure attribute required by the target. Use the setting expected by the site and test on the same HTTPS/HTTP scheme used in the script.
httponly A Boolean for an HttpOnly cookie. Set it through addCookie; page JavaScript cannot create an HttpOnly cookie.
expires (also documented as expiry in the cookie property documentation) An expiration value when the site requires one. Use the format accepted by the PhantomJS version installed with your CasperJS setup.

The PhantomJS reference lists these fields and recommends page.addCookie for setting cookies. Its property reference for page.cookies describes the cookies visible to the current URL.

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

Setting a cookie before a page action

The phrase “before opening a page” needs care. PhantomJS checks the cookie against the page context, so trying to add a cookie for a site while the current page is unrelated can fail. A dependable CasperJS sequence is:

  1. Open the target host with casper.start().
  2. Call this.page.addCookie() in that navigation callback.
  3. Check the Boolean return value.
  4. Use casper.thenOpen() to request the target again, or continue with the next navigation or interaction.

This sequence sets the cookie before the request that follows it, while keeping the current page’s domain aligned with the cookie’s domain. If a site needs a cookie on a subpath, set path to a value that covers that subpath rather than assuming that every URL will see it.

HttpOnly cookies and casper.evaluate()

casper.evaluate() executes JavaScript in the remote page’s DOM context, similar to entering code in that page’s browser console. That is a different mechanism from the PhantomJS WebPage API.

Use evaluate() only for a cookie that page JavaScript is allowed to create. Page JavaScript cannot create an HttpOnly cookie. When the cookie must carry the httponly attribute, supply it in the object passed to this.page.addCookie().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
casper.start('https://example.com/', function () {
    var added = this.page.addCookie({
        name: 'server_session',
        value: 'abc123',
        domain: 'example.com',
        path: '/',
        secure: true,
        httponly: true
    });

    this.echo('HttpOnly cookie accepted: ' + added);
});

casper.run();

Do not use a DOM-script workaround when the requirement is an HttpOnly cookie; it cannot create that attribute.

Why CasperJS cookies are rejected or appear to do nothing

Symptom Likely cause Fix
addCookie prints false The cookie domain does not match the current page, or another cookie attribute is not accepted for that page. Open the target host first, make domain match it, use a covering path, and test again while checking the Boolean result.
The call returns true, but the next request is unauthenticated The page was not reopened after the cookie was added, or the cookie is scoped to a different path. Navigate to the target again after addCookie and verify this.page.cookies on that URL.
The cookie is missing from page.cookies You inspected a URL outside the cookie’s domain or path. Inspect from the host and path covered by the cookie object.
A JavaScript assignment does not create the required cookie The cookie needs the HttpOnly attribute, which page JavaScript cannot set. Use this.page.addCookie() with httponly: true.
A secure-cookie flow behaves differently between environments The secure attribute and the URL scheme do not match the target’s expectations. Run against the same HTTPS or HTTP endpoint used by the real flow and set the documented attribute explicitly.
The script works on one site but not another Cookie policy, redirects, hostnames, paths, or authentication flows differ by site. Log the URL being opened, check the cookie’s domain and path, inspect the Boolean return, and verify visibility after each redirect.

A successful API call is not proof that the target application will authenticate the session. The application may require additional cookies, a particular path, a redirect sequence, or values generated by its own login flow. Validate the result on the actual page and request that consume the cookie.

Checking your CasperJS and PhantomJS versions

This technique belongs to a legacy stack. The official CasperJS repository states, “CasperJS is no longer actively maintained.” Its documentation is labeled 1.1.0-DEV, and PhantomJS’s cookie API is likewise a legacy WebPage interface. Confirm which CasperJS and PhantomJS binaries your script is actually using, then test the cookie flow against the target site rather than assuming modern-browser compatibility.

Neither the CasperJS project page nor the PhantomJS cookie references guarantee that a particular authentication flow, bot check, consent system, or modern web application will work in this environment. If the target depends on browser capabilities that PhantomJS does not provide, changing the cookie object alone will not resolve the incompatibility. See the CasperJS repository for the project’s maintenance status and documentation links.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 your actual goal is to capture a clean image or PDF of a page after your automation work, ScreenshotNeo provides a website screenshot API and MCP server. It removes cookie-consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Its response identifies the page verdict and billing status in headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

Use the endpoint with one GET request:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options and response details. The same request in Python is:

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)

And in 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 fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots, and every feature is available on every plan. Create a free ScreenshotNeo account to get started.

FAQ

Will this make CasperJS compatible with every modern website?

No. CasperJS is no longer actively maintained, and PhantomJS is a legacy browser engine. A correctly scoped cookie can still fail when the site requires browser features or an authentication sequence that this stack does not support.

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

Can I use page.cookies instead of addCookie to set a cookie?

No. page.cookies is the readable collection of cookies visible to the current URL. PhantomJS documents page.addCookie as the setting operation.

Frequently Asked Questions

Will this make CasperJS compatible with every modern website?

No. CasperJS is no longer actively maintained, and PhantomJS is a legacy browser engine. A correctly scoped cookie can still fail when the site requires browser features or an authentication sequence that this stack does not support.

Can I use page.cookies instead of addCookie to set a cookie?

No. page.cookies is the readable collection of cookies visible to the current URL. PhantomJS documents page.addCookie as the setting operation.

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.