ScreenshotNeo

BlogHow-to

How to Call JavaScript Functions in the CasperJS Browser Console

Use CasperJS evaluate() to call page JavaScript functions safely, pass arguments, handle timing errors, and capture clean pages with ScreenshotNeo.

By the ScreenshotNeo team30 September 20268 min read

How to Call JavaScript Functions in the CasperJS Browser Console

Direct answer: In CasperJS, call a JavaScript function that belongs to the opened page inside this.evaluate(), or queue it with thenEvaluate(). CasperJS runs your script in its own environment; the callback crosses into the page, where window, document, DOM nodes, and page-defined functions exist.

The CasperJS reference describes evaluate() as a gate between those environments: code in the callback runs as if entered in the browser console. This example calls a page function and returns its value:

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

casper.start('https://example.com/', function () {
    var result = this.evaluate(function (name) {
        return window.greet(name);
    }, 'Ada');

    this.echo('Result: ' + result);
});

casper.run();

The page must define window.greet before the evaluation runs. Replace the URL, function, and arguments with those used by your page.

1. Understand the two JavaScript contexts

There are two runtimes in a CasperJS program:

evaluate() crosses from the CasperJS script into the page context.
evaluate() crosses from the CasperJS script into the page context.
Context Available objects Typical work
CasperJS script casper, files, command-line arguments, control flow Navigation, waits, assertions, saving files
Opened page window, document, page globals, DOM nodes Calling app functions, reading or changing the DOM

A function declared by the site is not a function in the outer CasperJS scope. Calling it directly there causes a reference error or accesses an unrelated value. Pass a callback to evaluate() so CasperJS executes it in the remote page.

Arguments after the callback are copied into the page context. Use simple serializable values such as strings, numbers, booleans, arrays, and plain objects. A CasperJS variable, file handle, or Casper instance does not automatically become a page global.

2. Call a function immediately with evaluate()

Use evaluate() inside a step when the current page is ready and you need the return value immediately.

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

casper.start('https://example.com/', function () {
    var title = this.evaluate(function () {
        return document.title;
    });

    this.echo('Page title: ' + title);
});

casper.run();

Pass parameters after the callback:

casper.start('https://example.com/', function () {
    var total = this.evaluate(function (price, quantity) {
        return window.calculateTotal(price, quantity);
    }, 19.99, 2);

    this.echo('Total: ' + total);
});

You can also change the DOM and return a confirmation:

var changed = this.evaluate(function (selector, value) {
    var input = document.querySelector(selector);
    if (!input) return false;
    input.value = value;
    input.dispatchEvent(new Event('input', { bubbles: true }));
    return true;
}, '#email', 'ada@example.com');

this.echo(changed ? 'Input updated' : 'Input not found');

3. Queue page code with thenEvaluate()

thenEvaluate() queues the same page-context callback as part of the CasperJS step sequence:

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

casper.start('https://example.com/')
    .waitForSelector('#app')
    .thenEvaluate(function (name) {
        window.greet(name);
    }, 'Ada')
    .then(function () {
        this.echo('The page function was called.');
    })
    .run();

Use thenEvaluate() when the call belongs after earlier navigation or waits. Use evaluate() inside the current step when you need its result immediately.

Open and evaluate in one operation

CasperJS also documents thenOpenAndEvaluate(location, ...), a shortcut for opening a URL and evaluating against its remote DOM:

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

casper.start()
    .thenOpenAndEvaluate('https://example.com/', function (name) {
        return window.greet(name);
    }, 'Ada')
    .then(function () {
        this.echo('Evaluation completed.');
    })
    .run();

Use separate thenOpen(), waits, and thenEvaluate() steps when you need status checks or retries between navigation and execution.

4. Wait until the page function exists

Evaluation cannot call a function that has not loaded. Wait for a readiness selector:

casper.start('https://example.com/app')
    .waitForSelector('#app[data-ready="true"]')
    .thenEvaluate(function (id) {
        if (typeof window.loadRecord !== 'function') {
            return { ok: false, reason: 'loadRecord is undefined' };
        }
        return { ok: true, value: window.loadRecord(id) };
    }, 'record-42')
    .run();

When no reliable selector exists, wait for a page-side predicate with a timeout:

casper.start('https://example.com/app')
    .waitFor(function () {
        return this.evaluate(function () {
            return typeof window.loadRecord === 'function';
        });
    }, function () {
        this.evaluate(function () { window.loadRecord('record-42'); });
    }, function () {
        this.die('The page function did not become available in time.', 1);
    }, 10000)
    .run();

A selector or predicate is more reliable than a fixed delay because network and JavaScript execution times vary.

5. Return values and DOM data

Return plain data from the callback and assign the result outside:

var details = this.evaluate(function () {
    var heading = document.querySelector('h1');
    return {
        title: document.title,
        heading: heading ? heading.textContent.trim() : null,
        href: location.href
    };
});

this.echo(JSON.stringify(details));

DOM nodes, functions, cyclic objects, and browser handles are not useful across the boundary. Convert them inside the callback:

var state = this.evaluate(function () {
    var value = window.store && window.store.getState();
    return value ? { userId: value.user && value.user.id, ready: !!value.ready } : null;
});

6. Pass arguments safely

The documented positional form places arguments after the callback:

this.evaluate(function (selector, enabled) {
    var node = document.querySelector(selector);
    if (node) node.disabled = !enabled;
}, '#save', true);

Older examples use an object-style argument form. The API reference keeps it for compatibility but recommends positional arguments because the object form can fail in some cases. Pass user input as an argument instead of concatenating it into JavaScript source.

7. Use CasperJS page utilities

CasperJS injects __utils__. Its echo() helper writes from the page context to the CasperJS console:

casper.thenEvaluate(function () {
    __utils__.echo('Message from the page context');
});

Ordinary page functions do not require __utils__. The clientutils documentation also describes a bookmarklet that exposes these helpers in a regular browser console.

8. Complete CasperJS example

var casper = require('casper').create({
    verbose: true,
    logLevel: 'warning'
});

casper.start('https://example.com/dashboard');

casper.waitFor(function () {
    return this.evaluate(function () {
        return typeof window.refreshDashboard === 'function';
    });
}, function () {
    var result = this.evaluate(function (accountId) {
        var data = window.refreshDashboard(accountId);
        var heading = document.querySelector('h1');
        return {
            ok: true,
            summary: data && data.summary ? String(data.summary) : null,
            heading: heading ? heading.textContent.trim() : null
        };
    }, 'acct-123');

    this.echo(JSON.stringify(result));
}, function () {
    this.die('refreshDashboard was not defined after waiting.', 1);
}, 15000);

casper.run(function () {
    this.echo('Done.');
    this.exit();
});

Use syntax supported by the PhantomJS version bundled with your CasperJS installation. Replace newer syntax such as optional chaining with explicit null checks when necessary.

9. Troubleshooting

Symptom Cause Fix
ReferenceError The call ran in the CasperJS context. Move it inside evaluate() or thenEvaluate() and use window.functionName.
Function is undefined inside evaluate The bundle has not loaded, the route changed, or the function is module-scoped. Wait for a selector or predicate. If it is not on window, use the app’s public API or test hook.
document is undefined DOM code was placed outside the callback. Put DOM operations inside evaluated code.
Argument is undefined An outer variable was referenced without being passed. Add it after the callback and declare the matching parameter.
Return value is empty The callback forgot return or returned a non-serializable value. Return primitives or a plain object explicitly.
Call happens too early Asynchronous initialization is incomplete. Queue after navigation and wait for a selector or function predicate.
Input changes but the app ignores it The framework requires events. Dispatch the required input or change event, or call the app’s own function.
Script hangs A wait predicate never becomes true. Set a timeout, log the URL and predicate result, and fail explicitly.

10. Frames, security, and edge cases

An iframe is a separate document. A function in that frame is not available from the top page’s window. Same-origin frames can be reached through the frame document; cross-origin frames remain restricted by browser security rules. Treat a frame switch or navigation as a new execution context and verify the function there.

Single-page applications may replace routes without a full navigation. Check getCurrentUrl(), wait for a route-specific selector, and call the function only after the new view is ready. A page function may also be overwritten during hot reload or deferred initialization, so a function-exists predicate is safer than assuming the first script load completed.

11. Reliability, performance, and maintenance

  • Prefer selectors, data attributes, or function predicates over arbitrary sleeps.
  • Keep evaluated callbacks small and gather related fields in one call to reduce round trips.
  • Return only the fields you need; large serialized objects increase transfer and parsing work.
  • Set bounded timeouts so batch jobs cannot stall forever.
  • Log the URL and a compact result when diagnosing route or timing failures.
  • CasperJS and PhantomJS are legacy tools. Modern JavaScript syntax, site security policies, bot checks, and cross-origin content may prevent a function from being available even when the page works in a current browser.

CasperJS also means managing the browser process, dependencies, concurrency, memory, and failure retries yourself. Fixed delays waste time, while too many parallel sessions can exhaust resources.

12. Or skip the browser setup

If your goal is a clean image or PDF rather than executing an in-page function, ScreenshotNeo provides a single HTTP request. Before capture it accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and billing status.

ScreenshotNeo removes common consent and overlay elements before billing for a clean shot.
ScreenshotNeo removes common consent and overlay elements before billing for a clean shot.

See the ScreenshotNeo API documentation for full-page and element capture, device presets, dark mode, custom CSS and JavaScript, waits, request blocking, headers, cookies, geolocation, PDF output, caching, signed links, asynchronous jobs, bulk capture, usage reporting, and the OpenAPI specification.

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(`HTTP ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await Bun.write('shot.webp', bytes);

ScreenshotNeo also has an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. Every feature is included on every plan: 1,000 shots per month are free with no card, and paid plans start at $5 for 3,000 shots. Yearly billing gives two months free.

Create a free ScreenshotNeo account and start with the 1,000-shot monthly allowance.

13. FAQ

Can I call a function declared with let or const?

Only if the page exposes it on window or another reachable object. Top-level module bindings are not window globals.

Why does evaluate return undefined?

The callback likely has no return, or the value cannot be serialized. Return a primitive or plain object explicitly.

Should I use evaluate or thenEvaluate?

Use evaluate() for an immediate call inside the current step and thenEvaluate() to queue the call in the workflow.

Can evaluated code access CasperJS variables?

Only values passed as callback arguments cross the boundary. Pass data explicitly.

Does this open a real developer-tools console?

No. It executes code in the page context with the DOM access model of a browser console while CasperJS remains the outer automation script.