Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

2578 lines (2106 sloc) 94.521 kb
<!DOCTYPE html><html><head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="robots" content="index, follow">
<link rel="canonical" href="http://casperjs.org/">
<title>API documentation | CasperJS 1.0.0-RC1</title>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="keywords" content="phantomjs, phantom, casperjs, casper, browser, javascript, navigation, scripting, test, testing, scrape, scraping">
<meta name="description" content="CasperJS is a browser navigation scripting &amp; testing utility written in Javascript on top of PhantomJS.">
<meta name="google-site-verification" content="SEcGmVv4IsGYP6-xMJquQcrUrYjIZNXyX0VGfly2m1o">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Asap:400,700,400italic,700italic&amp;subset=latin,latin-ext">
<link rel="stylesheet" href="prettify/prettify.css?1348471995809">
<link rel="stylesheet" href="css/casper.css?1348471995809">
<link rel="shortcut icon" href="favicon.ico">
</head>
<body>
<a href="http://github.com/n1k0/casperjs" class="contribute">
<img src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png" alt="Fork me on GitHub">
</a>
<div class="navbar navbar-fixed-top" id="topbar">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="./index.html">CasperJS</a>
<div class="nav-collapse">
<ul class="nav">
<li><a href="installation.html">Install</a></li>
<li><a href="quickstart.html">Quickstart</a></li>
<li class="dropdown active" id="api-menu">
<a class="dropdown-toggle" data-toggle="dropdown" data-target="#api-menu" href="api.html">
<abbr title="Application Programming Interface">API</abbr>
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="active"><a href="api.html#intro">Home</a></li>
<li class="divider"></li>
<li class="active"><a href="api.html#casper">Casper API</a></li>
<li class="active"><a href="api.html#client-utils">Client-side utils</a></li>
<li class="active"><a href="api.html#colorizer">Colorizer API</a></li>
<li class="active"><a href="api.html#tester">Tester API</a></li>
<li class="active"><a href="api.html#utils">Utils API</a></li>
</ul>
</li>
<li><a href="cli.html"><abbr title="Command Line Interface">CLI</abbr></a></li>
<li><a href="selectors.html">Selectors</a></li>
<li><a href="events-filters.html">Events</a></li>
<li><a href="logging.html">Logging</a></li>
<li><a href="extending.html">Extending</a></li>
<li><a href="testing.html">Testing</a></li>
<li><a href="debugging.html">Debugging</a></li>
<li><a href="faq.html"><abbr title="Frequently Asked Questions">FAQ</abbr></a></li>
<li><a href="https://groups.google.com/forum/#!forum/casperjs">Support</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container" id="overview">
<div class="content"><section id="intro">
<div class="page-header">
<h1>
<span class="section-title">Api documentation</span>
</h1>
</div>
<div class="section-content">
<p>
This page details the APIs of the following CasperJS classes &amp;
modules, as well as their usage:
</p>
<div class="subnav">
<ul class="nav nav-pills">
<li><a href="api.html#casper">The Casper class</a></li>
<li><a href="api.html#client-utils">The client-side utils</a></li>
<li><a href="api.html#colorizer">The Colorizer API</a></li>
<li><a href="api.html#tester">The Tester API</a></li>
<li><a href="api.html#utils">The utils API</a></li>
</ul>
</div>
</div>
</section>
<section id="casper">
<div class="page-header">
<h1>
<span class="section-title">The Casper class</span>
</h1>
</div>
<div class="row">
<div class="span9 api-content"><p>Casper source code is quite heavily documented using <code>jsdoc</code>, but below
you'll find the whole API documentation with sample code.
</p>
<h2>The Casper class</h2>
<p>The most easy way to instantiate a casper instance is to use the
module's <code>create()</code> method:
</p>
<pre><code class="javascript">var casper = require('casper').create();</code></pre>
<p>But you can also retrieve the main Function and instantiate it by
yourself:
</p>
<pre><code class="javascript">var casper = new require('casper').Casper();</code></pre>
<p><span class="label label-info">Hint</span>
Also, check out <a href="extending.html">how to extend Casper with your own methods</a>.
</p>
<h3 id="casper.options"><code>Casper([Object options])</code></h3>
<p>Both the <code>Casper</code> constructor and the <code>create()</code> function accept a
single <code>options</code> argument which is a standard javascript object:
</p>
<pre><code class="javascript">var casper = require('casper').create({
verbose: true,
logLevel: "debug"
});</code></pre>
<h2>Casper options</h2>
<p>All the available options are detailed below:
</p>
<table class="table table-striped table-condensed" caption="Casper options">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>clientScripts</code></td>
<td><code>Array</code></td>
<td><code>[]</code></td>
<td>
A collection of script filepaths to include to every
page loaded
</td>
</tr>
<tr>
<td><code>exitOnError</code></td>
<td><code>Boolean</code></td>
<td><code>true</code></td>
<td>
Sets if CasperJS must exit when an uncaught error has been thrown by
the script.
</td>
</tr>
<tr>
<td><code>httpStatusHandlers</code></td>
<td><code>Object</code></td>
<td><code>{}</code></td>
<td>
A javascript Object containing functions to call when a
requested resource has a given HTTP status code. A
<a href="https://github.com/n1k0/casperjs/blob/master/samples/statushandlers.js">dedicated
sample</a> is provided as an example.
</td>
</tr>
<tr>
<td><code>logLevel</code></td>
<td><code>String</code></td>
<td><code>"error"</code></td>
<td>
Logging level (see the <a href="logging.html">logging
section</a> for more information)
</td>
</tr>
<tr>
<td><code>onAlert</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td>
A function to be called when a javascript <code>alert()</code>
is triggered
</td>
</tr>
<tr>
<td><code>onDie</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td>
A function to be called when <code>Casper#die()</code>
is called
</td>
</tr>
<tr>
<td><code>onError</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td>
A function to be called when an <code>"error"</code>
level event occurs
</td>
</tr>
<tr>
<td><code>onLoadError</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td>
A function to be called when a requested resource cannot
be loaded
</td>
</tr>
<tr>
<td><code>onPageInitialized</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td>A function to be called after <code>WebPage</code>
instance has been initialized</td>
</tr>
<tr>
<td><code>onResourceReceived</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td>
Proxy method for PhantomJS' <code>WebPage#onResourceReceived()</code>
callback, but the current Casper instance is passed as
first argument.
</td>
</tr>
<tr>
<td><code>onResourceRequested</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td>
Proxy method for PhantomJS' <code>WebPage#onResourceRequested()</code>
callback, but the current Casper instance is passed as
first argument.
</td>
</tr>
<tr>
<td><code>onStepComplete</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td>A function to be executed when a step function execution
is finished.</td>
</tr>
<tr>
<td><code>onStepTimeout</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td> A function to be executed when a step function
execution time exceeds the value of the <code>stepTimeout</code>
option, if any has been set. </td>
</tr>
<tr>
<td><code>onTimeout</code></td>
<td><code>Function</code></td>
<td><code>null</code></td>
<td> A function to be executed when script execution time
exceeds the value of the <code>timeout</code> option, if
any has been set. </td>
</tr>
<tr>
<td><code>page</code></td>
<td><code>WebPage</code></td>
<td><code>null</code></td>
<td>An existing <code>WebPage</code> instance</td>
</tr>
<tr>
<td><code>pageSettings</code></td>
<td><code>Object</code></td>
<td><code>{}</code></td>
<td>
<p>
PhantomJS's <code>WebPage</code> settings object.
<a href="http://code.google.com/p/phantomjs/wiki/Interface#settings_(object)">Available settings</a> are:
</p>
<ul>
<li>
<code>javascriptEnabled</code> defines whether to execute the
script in the page or not (default to true)
</li>
<li>
<code>loadImages</code> defines whether to load the inlined images
or not
</li>
<li>
<code>loadPlugins</code> defines whether to load NPAPI plugins
(Flash, Silverlight, ...) or not
</li>
<li>
<code>localToRemoteUrlAccessEnabled</code> defines whether local
resource (e.g. from file) can access remote URLs or not (default to false)
</li>
<li>
<code>userAgent</code> defines the user agent sent to server when
the web page requests resources.
</li>
<li>
<code>userName</code> sets the user name used for HTTP
authentication
</li>
<li>
<code>password</code> sets the password used for HTTP
authentication
</li>
<li>
<code>XSSAuditingEnabled</code> defines whether load requests
should be monitored for cross-site scripting attempts (default to
false)
</li>
</ul>
</td>
</tr>
<tr>
<td><code>safeLogs</code></td>
<td><code>Boolean</code></td>
<td><code>true</code></td>
<td>
<span class="label label-success">Added in 1.0</span>
When this option is set to <code>true</code>&nbsp;— which is the
default, any password information entered in
<code>&lt;input type="password"&gt;</code> will be obfuscated in log
messages. Set <code>safeLogs</code> to false to disclose passwords in
plain text <strong>(not recommended)</strong>.
</td>
</tr>
<tr>
<td><code>stepTimeout</code></td>
<td><code>Number</code></td>
<td><code>null</code></td>
<td> Max step timeout in milliseconds; when set, every
defined step function will have to execute before this
timeout value has been reached. You can define the <code>onStepTimeout()</code>
callback to catch such a case. By default, the script will
<code>die()</code> with an error message. </td>
</tr>
<tr>
<td><code>timeout</code></td>
<td><code>Number</code></td>
<td><code>null</code></td>
<td>Max timeout in milliseconds</td>
</tr>
<tr>
<td><code>verbose</code></td>
<td><code>Boolean</code></td>
<td><code>false</code></td>
<td>Realtime output of log messages</td>
</tr>
<tr>
<td><code>viewportSize</code></td>
<td><code>Object</code></td>
<td><code>null</code></td>
<td>Viewport size, eg. <code>{width: 800, height: 600}</code></td>
</tr>
</tbody>
</table>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">var casper = require('casper').create({
clientScripts: [
'includes/jquery.js', // These two scripts will be injected in remote
'includes/underscore.js' // DOM on every request
],
logLevel: "info", // Only "info" level messages will be logged
onError: function(self, m) { // Any "error" level message will be written
console.log('FATAL:' + m); // on the console output and PhantomJS will
self.exit(); // terminate
},
pageSettings: {
loadImages: false, // The WebPage instance used by Casper will
loadPlugins: false // use these settings
}
});</code></pre>
<p>But no worry, usually you'll just need to instantiate Casper using
<code>require('casper').create()</code>.
</p>
<h3 id="casper.back"><code>Casper#back()</code></h3>
<p>Moves back a step in browser's history.
</p>
<pre><code class="javascript">casper.start('http://foo.bar/1')
casper.thenOpen('http://foo.bar/2');
casper.thenOpen('http://foo.bar/3');
casper.back();
casper.run(function() {
console.log(this.getCurrentUrl()); // 'http://foo.bar/2'
});</code></pre>
<p>Also have a look at <a href="#forward"><code>Casper.forward()</code></a>.
</p>
<h3 id="casper.base64encode"><code>Casper#base64encode(String url [, String method, Object data])</code></h3>
<p>Encodes a resource using the base64 algorithm synchronously using
client-side XMLHttpRequest.
</p>
<p><span class="label label-info">Note</span> We cannot use <code>window.btoa()</code>
because it fails miserably in the version of WebKit shipping with PhantomJS.
</p>
<p>Example: retrieving google logo image encoded in base64:
</p>
<pre><code class="javascript">var base64logo = null;
casper.start('http://www.google.fr/', function() {
base64logo = this.base64encode('http://www.google.fr/images/srpr/logo3w.png');
});
casper.run(function() {
this.echo(base64logo).exit();
});</code></pre>
<p>You can also perform an HTTP POST request to retrieve the contents to
encode:
</p>
<pre><code class="javascript">var base46contents = null;
casper.start('http://domain.tld/download.html', function() {
base46contents = this.base64encode('http://domain.tld/', 'POST', {
param1: 'foo',
param2: 'bar'
});
});</code></pre>
<pre><code class="javascript">casper.run(function() {
this.echo(base46contents).exit();
});</code></pre>
<h3 id="casper.click"><code>Casper#click(String <a href="selectors.html">selector</a>)</code></h3>
<p>Performs a click on the element matching the provided <a href="selectors.html">selector expression</a>.
The method tries two strategies sequentially:
</p>
<ol>
<li>trying to trigger a MouseEvent in Javascript</li>
<li>using native QtWebKit event if the previous attempt failed</li>
</ol>
<p>Example:
</p>
<pre><code class="javascript">casper.start('http://google.fr/');
casper.thenEvaluate(function(term) {
document.querySelector('input[name="q"]').setAttribute('value', term);
document.querySelector('form[name="f"]').submit();
}, { term: 'CasperJS' });
casper.then(function() {
// Click on 1st result link
this.click('h3.r a');
});
casper.then(function() {
console.log('clicked ok, new location is ' + this.getCurrentUrl());
});
casper.run();</code></pre>
<h3 id="casper.clickLabel"><code>Casper#clickLabel(String label[, String tag])</code></h3>
<p><span class="label label-success">Added in 0.6.10</span>
Clicks on the first DOM element found containing <code>label</code> text.
Optionaly ensures that the element node name is <code>tag</code>.
</p>
<pre><code class="javascript">// &lt;a href="..."&gt;My link is beautiful&lt;/a&gt;
casper.then(function() {
this.clickLabel('My link is beautiful', 'a');
});
// &lt;button type="submit"&gt;But my button is sexier&lt;/button&gt;
casper.then(function() {
this.clickLabel('But my button is sexier', 'button');
});</code></pre>
<h3 id="casper.capture"><code>Casper#capture(String targetFilepath, Object clipRect)</code></h3>
<p>Proxy method for PhantomJS' <code>WebPage#render</code>. Adds a clipRect parameter
for automatically setting page clipRect setting values and sets it back
once done.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.capture('google.png', {
top: 100,
left: 100,
width: 500,
height: 400
});
});
casper.run();</code></pre>
<h3 id="casper.captureBase64"><code>Casper#captureBase64(String format[, Mixed area])</code></h3>
<p><span class="label label-success">Added in 0.6.5</span>
<span class="label label-info">PhantomJS &gt;= 1.6</span>
Computes the <a href="http://en.wikipedia.org/wiki/Base64">Base64</a> representation of a
binary image capture of the current page, or an area within the page, in a
given format.
</p>
<p>Supported image formats are <code>bmp</code>, <code>jpg</code>, <code>jpeg</code>, <code>png</code>, <code>ppm</code>, <code>tiff</code>,
<code>xbm</code> and <code>xpm</code>.
</p>
<p>The <code>area</code> argument can be either of the following types:
</p>
<ul>
<li><code>String</code>: area is a CSS3 selector string, eg. <code>div#plop form[name="form"] input[type="submit"]</code></li>
<li><code>clipRect</code>: area is a clipRect object, eg. <code>{"top":0,"left":0,"width":320,"height":200}</code></li>
<li><p><code>Object</code>: area is a <a href="selectors.html">selector object</a>, eg. an XPath selector</p>
</li>
<li><p><em>Example:*</em></p>
</li>
</ul>
<pre><code class="javascript">casper.start('http://google.com', function() {
// selector capture
console.log(this.captureBase64('png', '#lga'));
// clipRect capture
console.log(this.captureBase64('png', {
top: 0,
left: 0,
width: 320,
height: 200
}));
// whole page capture
console.log(this.captureBase64('png'));
});
casper.run();</code></pre>
<h3 id="casper.captureSelector"><code>Casper#captureSelector(String targetFile, String <a href="selectors.html">selector</a>)</code></h3>
<p>Captures the page area containing the provided selector.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.weather.com/', function() {
this.captureSelector('weather.png', '.twc-story-block');
});
casper.run();</code></pre>
<h3 id="casper.clear"><code>Casper#clear()</code></h3>
<p><span class="label label-success">Added in 0.6.5</span>
Clears the current page execution environment context. Useful to avoid
having previously loaded DOM contents being still active.
</p>
<p>Think of it as a way to stop javascript execution within the remote DOM
environment.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.clear(); // javascript execution in this page has been stopped
});
casper.then(function() {
// ...
});
casper.run();</code></pre>
<h3 id="casper.debugHTML"><code>Casper#debugHTML()</code></h3>
<p>Logs the HTML code of the current page directly to the standard output,
for debugging purpose.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.debugHTML();
});
casper.run();</code></pre>
<h3 id="casper.debugPage"><code>Casper#debugPage()</code></h3>
<p>Logs the textual contents of the current page directly to the standard
output, for debugging purpose.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.debugPage();
});
casper.run();</code></pre>
<h3 id="casper.die"><code>Casper#die(String message[, int status])</code></h3>
<p>Exits phantom with a logged error message and an optional exit status
code.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.die("Fail.", 1);
});
casper.run();</code></pre>
<h3 id="casper.download"><code>Casper#download(String url, String target[, String method, Object data])</code></h3>
<p>Saves a remote resource onto the filesystem. You can optionally set the HTTP
method using the <code>method</code> argument, and pass request arguments through the
<code>data</code> object (see <a href="api.html#casper.base64encode">base64encode</a>).
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
var url = 'http://www.google.fr/intl/fr/about/corporate/company/';
this.download(url, 'google_company.html');
});
casper.run(function() {
this.echo('Done.').exit();
});</code></pre>
<h3 id="casper.each"><code>Casper#each(Array array, Function fn)</code></h3>
<p>Iterates over provided array items and execute a callback.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">var links = [
'http://google.com/',
'http://yahoo.com/',
'http://bing.com/'
];
casper.start().each(links, function(self, link) {
self.thenOpen(link, function() {
this.echo(this.getTitle());
});
});
casper.run();</code></pre>
<p><span class="label label-info">Hint</span> Have a look at the
<a href="https://github.com/n1k0/casperjs/blob/master/samples/googlematch.js">googlematch.js</a>
sample script for a concrete use case.
</p>
<h3 id="casper.echo"><code>Casper#echo(String message[, String style])</code></h3>
<p>Prints something to stdout, optionally with some fancy color (see the
<a href="#colorizer#"><code>Colorizer</code></a> section of this document for more
information).
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.echo('Page title is: ' + this.evaluate(function() {
return document.title;
}), 'INFO'); // Will be printed in green on the console
});
casper.run();</code></pre>
<h3 id="casper.evaluate"><code>Casper#evaluate(Function fn[, Object replacements])</code></h3>
<p>Evaluates an expression <strong>in the remote page context</strong>, a bit like what PhantomJS'
<code>WebPage#evaluate</code> does, but can also handle passed arguments if you
define their context:
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.evaluate(function(username, password) {
document.querySelector('#username').value = username;
document.querySelector('#password').value = password;
document.querySelector('#submit').click();
}, {
username: 'sheldon.cooper',
password: 'b4z1ng4'
});</code></pre>
<p><span class="label label-info">Note</span> For filling and submitting forms, rather use the
<a href="#casper.fill"><code>Casper#fill()</code></a> method.
</p>
<p><span class="label label-info">Note</span> The concept behind this method is
probably the most difficult to understand when discovering CasperJS.
As a reminder, think of the <code>evaluate()</code> method as a <em>gate</em> between the CasperJS
environment and the one of the page you have opened; everytime you pass a closure to
<code>evaluate()</code>, you're entering the page and execute code as if you were using the
browser console.
</p>
<p>Here's a quickly drafted diagram trying to basically explain the separation of
concerns:
</p>
<p><img src="images/evaluate-diagram.png" alt="diagram">
</p>
<h3 id="casper.evaluateOrDie"><code>Casper#evaluateOrDie(Function fn[, String message])</code></h3>
<p>Evaluates an expression within the current page DOM and <code>die()</code> if it
returns anything but <code>true</code>.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://foo.bar/home', function() {
this.evaluateOrDie(function() {
return /logged in/.match(document.title);
}, 'not authenticated');
});
casper.run();</code></pre>
<h3 id="casper.exit"><code>Casper#exit([int status])</code></h3>
<p>Exits PhantomJS with an optional exit status code.
</p>
<h3 id="casper.exists"><code>Casper#exists(String <a href="selectors.html">selector</a>)</code></h3>
<p>Checks if any element within remote DOM matches the provided
<a href="selectors.html">selector</a>.
</p>
<pre><code class="javascript">casper.start('http://foo.bar/home', function() {
if (this.exists('#my_super_id')) {
this.echo('found #my_super_id', 'INFO');
} else {
this.echo('#my_super_id not found', 'ERROR');
}
});
casper.run();</code></pre>
<h3 id="casper.fetchText"><code>Casper#fetchText(String <a href="selectors.html">selector</a>)</code></h3>
<p>Retrieves text contents matching a given <a href="selectors.html">selector expression</a>.
If you provide one matching more than one element, their textual contents will
be concatenated.
</p>
<pre><code class="javascript">casper.start('http://google.com/search?q=foo', function() {
this.echo(this.fetchText('h3'));
}).run();</code></pre>
<h3 id="casper.forward"><code>Casper#forward()</code></h3>
<p>Moves a step forward in browser's history.
</p>
<pre><code class="javascript">casper.start('http://foo.bar/1')
casper.thenOpen('http://foo.bar/2');
casper.thenOpen('http://foo.bar/3');
casper.back(); // http://foo.bar/2
casper.back(); // http://foo.bar/1
casper.forward(); // http://foo.bar/2
casper.run();</code></pre>
<p>Also have a look at <a href="#back"><code>Casper.back()</code></a>.
</p>
<h3 id="casper.log"><code>Casper#log(String message[, String level, String space])</code></h3>
<p>Logs a message with an optional level in an optional space. Available
levels are <code>debug</code>, <code>info</code>, <code>warning</code> and <code>error</code>. A space is a kind of
namespace you can set for filtering your logs. By default, Casper logs
messages in two distinct spaces: <code>phantom</code> and <code>remote</code>, to distinguish
what happens in the PhantomJS environment from the remote one.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.log("I'm logging an error", "error");
});
casper.run();</code></pre>
<h3 id="casper.fill"><code>Casper#fill(String <a href="selectors.html">selector</a>, Object values[, Boolean submit])</code></h3>
<p>Fills the fields of a form with given values and optionally submits it.
</p>
<p>Example with this sample html form:
</p>
<pre><code class="html">&lt;form action="/contact" id="contact-form" enctype="multipart/form-data"&gt;
&lt;input type="text" name="subject"/&gt;
&lt;textearea name="content"&gt;&lt;/textearea&gt;
&lt;input type="radio" name="civility" value="Mr"/&gt; Mr
&lt;input type="radio" name="civility" value="Mrs"/&gt; Mrs
&lt;input type="text" name="name"/&gt;
&lt;input type="email" name="email"/&gt;
&lt;input type="file" name="attachment"/&gt;
&lt;input type="checkbox" name="cc"/&gt; Receive a copy
&lt;input type="submit"/&gt;
&lt;/form&gt;</code></pre>
<p>A script to fill and submit this form:
</p>
<pre><code class="javascript">casper.start('http://some.tld/contact.form', function() {
this.fill('form#contact-form', {
'subject': 'I am watching you',
'content': 'So be careful.',
'civility': 'Mr',
'name': 'Chuck Norris',
'email': 'chuck@norris.com',
'cc': true,
'attachment': '/Users/chuck/roundhousekick.doc'
}, true);
});
casper.then(function() {
this.evaluateOrDie(function() {
return /message sent/.test(document.body.innerText);
}, 'sending message failed');
});
casper.run(function() {
this.echo('message sent').exit();
});</code></pre>
<p>Please Don't use CasperJS nor PhantomJS to send spam, or I'll be calling
the Chuck. More seriously, please just don't.
</p>
<p><span class="label label-warning">Warning</span> The <code>fill()</code> method currently
can't fill <strong>file fields using XPath selectors</strong>; PhantomJS natively only allows
the use of CSS3 selectors in
<a href="http://code.google.com/p/phantomjs/wiki/Interface#uploadFile(selector,_fileName)">its
uploadFile method</a>, hence this limitation.
</p>
<h3 id="casper.getCurrentUrl"><code>Casper#getCurrentUrl()</code></h3>
<p>Retrieves current page URL. <span class="label label-info">Note</span> the url
will be url-decoded.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.echo(this.getCurrentUrl()); // "http://www.google.fr/"
});
casper.run();</code></pre>
<h3 id="casper.getElementAttribute"><code>Casper#getElementAttribute(String <a href="selectors.html">selector</a>, String attribute)</code></h3>
<p><span class="label label-success">Added in 1.0</span>
Retrieves the value of an attribute on the first element matching the provided
<a href="selectors.html">selector</a>.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
require('utils').dump(this.getElementAttribute('div[title="Google"]', 'title')); // "Google"
});
casper.run();</code></pre>
<h3 id="casper.getElementBounds"><code>Casper#getElementBounds(String <a href="selectors.html">selector</a>)</code></h3>
<p>Retrieves boundaries for a DOM element matching the provided
<a href="selectors.html">selector</a>.
</p>
<p>It returns an Object with four keys: <code>top</code>, <code>left</code>, <code>width</code> and <code>height</code>, or
<code>null</code> if the selector doesn't exist.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
require('utils').dump(this.getElementBounds('div[title="Google"]'));
});
casper.run();</code></pre>
<p>This will output something like:
</p>
<pre><code>{
"height": 95,
"left": 352,
"top": 16,
"width": 275
}</code></pre>
<h3 id="casper.getGlobal"><code>Casper#getGlobal(String name)</code></h3>
<p>Retrieves a global variable value within the remote DOM environment by
its name. Basically, <code>getGlobal('foo')</code> will retrieve the value of <code>window.foo</code>
from the page.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.echo(this.getGlobal('innerWidth')); // 1024
});
casper.run();</code></pre>
<h3 id="casper.getPageContent"><code>Casper#getPageContent()</code></h3>
<p><span class="label label-success">Added in 1.0.0</span>
Retrieves current page contents, dealing with exotic other content types than HTML.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start().then(function() {
this.open('http://search.twitter.com/search.json?q=casperjs', {
method: 'get',
headers: {
'Accept': 'application/json'
}
});
});
casper.run(function() {
require('utils').dump(JSON.parse(this.getPageContent()));
this.exit();
});</code></pre>
<h3 id="casper.getTitle"><code>Casper#getTitle()</code></h3>
<p>Retrieves current page title.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.echo(this.getTitle()); // "Google"
});
casper.run();</code></pre>
<h3 id="casper.mouseEvent"><code>Casper#mouseEvent(String type, String <a href="selectors.html">selector</a>)</code></h3>
<p><span class="label label-success">Added in 0.6.9</span>
Triggers a mouse event on the first element found matching the provided
selector.
</p>
<p>Supported events are <code>mouseup</code>, <code>mousedown</code>, <code>click</code>, <code>mousemove</code>, <code>mouseover</code>
and <code>mouseout</code>.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.fr/', function() {
this.mouseEvent('click', 'h2 a');
});
casper.run();</code></pre>
<h3 id="casper.open"><code>Casper#open(String location, Object Settings)</code></h3>
<p>Performs an HTTP request for opening a given location. You can forge
<code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code> and <code>HEAD</code> requests.
</p>
<p><strong>Example for a standard <code>GET</code> request:</strong>
</p>
<pre><code class="javascript">casper.start();
casper.open('http://www.google.com/').then(function() {
this.echo('GOT it.');
});
casper.run();</code></pre>
<p><strong>Example for a <code>POST</code> request:</strong>
</p>
<pre><code class="javascript">casper.start();
casper.open('http://some.testserver.com/post.php', {
method: 'post',
data: {
'title': 'Plop',
'body': 'Wow.'
}
});
casper.then(function() {
this.echo('POSTED it.');
});
casper.run();</code></pre>
<p>To pass nested parameters arrays:
</p>
<pre><code class="javascript">casper.open('http://some.testserver.com/post.php', {
method: 'post',
data: {
'standard_param': 'foo',
'nested_param[]': [ // please note the use of square brackets!
'Something',
'Something else'
]
}
});</code></pre>
<p><span class="label label-success">Added in 1.0</span>
<span class="label label-info">PhantomJS &gt;= 1.6</span>
You can also set custom request headers to send when performing an outgoing
request, passing the <code>headers</code> option:
</p>
<pre><code class="javascript">casper.open('http://some.testserver.com/post.php', {
method: 'post',
data: {
'title': 'Plop',
'body': 'Wow.'
},
headers: {
'Accept-Language': 'fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3'
}
});</code></pre>
<h3 id="casper.reload"><code>Casper#reload([Function then])</code></h3>
<p><span class="label label-success">Added in 1.0</span>
Reloads current page location.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://google.com', function() {
this.echo("loaded");
this.reload(function() {
this.echo("loaded again");
});
});
casper.run();</code></pre>
<h3 id="casper.repeat"><code>Casper#repeat(int times, function then)</code></h3>
<p>Repeats a navigation step a given number of times.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start().repeat(3, function() {
this.echo("Badger");
});
casper.run();</code></pre>
<h3 id="casper.resourceExists"><code>Casper#resourceExists(Mixed test)</code></h3>
<p>Checks if a resource has been loaded. You can pass either a function or
a string to perform the test.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://www.google.com/', function() {
if (this.resourceExists('logo3w.png')) {
this.echo('Google logo loaded');
} else {
this.echo('Google logo not loaded', 'ERROR');
}
});
casper.run();</code></pre>
<p><span class="label label-info">Note</span> If you want to wait for a resource to
be loaded, use the <a href="#casper.waitForResource"><code>waitForResource()</code></a> method.
</p>
<h3 id="casper.run"><code>Casper#run(fn onComplete[, int time])</code></h3>
<p>Runs the whole suite of steps and optionally executes a callback when
they've all been done. Obviously, <strong>calling this method is mandatory</strong>
in order to run the Casper navigation suite.
</p>
<p>Casper suite <strong>won't run</strong>:
</p>
<pre><code class="javascript">casper.start('http://foo.bar/home', function() {
// ...
});
// hey, it's missing .run() here!</code></pre>
<p>Casper suite <strong>will run</strong>:
</p>
<pre><code class="javascript">casper.start('http://foo.bar/home', function() {
// ...
});
casper.run();</code></pre>
<p><code>Casper.run()</code> also accepts an <code>onComplete</code> callback, which you can
consider as a custom final step to perform when all the other steps have
been executed. Just don't forget to <code>exit()</code> Casper if you define one!
</p>
<pre><code class="javascript">casper.start('http://foo.bar/home', function() {
// ...
});
casper.then(function() {
// ...
});
casper.run(function() {
this.echo('So the whole suite ended.');
this.exit(); // &lt;--- don't forget me!
});</code></pre>
<h3 id="casper.setHttpAuth"><code>Casper#setHttpAuth(String username, String password)</code></h3>
<p>Sets <code>HTTP_AUTH_USER</code> and <code>HTTP_AUTH_PW</code> values for HTTP based authentication
systems.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start();
casper.setHttpAuth('sheldon.cooper', 'b4z1ng4');
casper.thenOpen('http://password-protected.domain.tld/', function() {
this.echo("I'm in. Bazinga.");
})
casper.run();</code></pre>
<p>Of course you can directly pass the auth string in the url to open:
</p>
<pre><code class="javascript">var url = 'http://sheldon.cooper:b4z1ng4@password-protected.domain.tld/';
casper.start(url, function() {
this.echo("I'm in. Bazinga.");
})
casper.run();</code></pre>
<h3 id="casper.start"><code>Casper#start(String url[, function then])</code></h3>
<p>Configures and starts Casper, then open the provided <code>url</code> and
optionally adds the step provided by the <code>then</code> argument.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://google.fr/', function() {
this.echo("I'm loaded.");
});
casper.run();</code></pre>
<p>Alternatively:
</p>
<pre><code class="javascript">casper.start('http://google.fr/');
casper.then(function() {
this.echo("I'm loaded.");
});
casper.run();</code></pre>
<p>Or alternatively:
</p>
<pre><code class="javascript">casper.start('http://google.fr/');
casper.then(function() {
casper.echo("I'm loaded.");
});
casper.run();</code></pre>
<p>Or even:
</p>
<pre><code class="javascript">casper.start('http://google.fr/');
casper.then(function(self) {
self.echo("I'm loaded.");
});
casper.run();</code></pre>
<p>Matter of taste!
</p>
<p><span class="label label-info">Note</span> <strong>You must call the <code>start()</code> method
in order to be able to add navigation steps</strong> and run the suite. If you don't
you'll get an error message inviting you to do so anyway.
</p>
<h3 id="casper.then"><code>Casper#then(Function fn)</code></h3>
<p>This method is the standard way to add a new navigation step to the stack, by
providing a simple function:
</p>
<pre><code class="javascript">casper.start('http://google.fr/');
casper.then(function() {
this.echo("I'm in your google.");
});
casper.then(function() {
this.echo('Now, let me write something');
});
casper.then(function() {
this.echo('Oh well.');
});
casper.run();</code></pre>
<p>You can add as many steps as you need. Note that the current <code>Casper</code> instance
automatically binds the <code>this</code> keyword for you within step functions.
</p>
<p>To run all the steps you defined, call the <a href="#run"><code>run()</code></a> method,
and voila.
</p>
<p><span class="label label-info">Note</span> You must <a href="#start"><code>start()</code></a>
the casper instance in order to use the <code>then()</code> method.
</p>
<h3 id="casper.thenEvaluate"><code>Casper#thenEvaluate(Function fn[, Object replacements])</code></h3>
<p>Adds a new navigation step to perform code evaluation within the current
retrieved page DOM.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">// Querying for "Chuck Norris" on Google
casper.start('http://google.fr/').thenEvaluate(function(term) {
document.querySelector('input[name="q"]').setAttribute('value', term);
document.querySelector('form[name="f"]').submit();
}, {
term: 'Chuck Norris'
});
casper.run();</code></pre>
<p>This method is basically a convenient a shortcut for chaining a
<a href="#then"><code>then()</code></a> and an <a href="#evaluate"><code>evaluate()</code></a>
calls.
</p>
<h3 id="casper.thenOpen"><code>Casper#thenOpen(String location[, mixed options])</code></h3>
<p>Adds a new navigation step for opening a new location, and optionally
add a next step when its loaded.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://google.fr/').then(function() {
this.echo("I'm in your google.");
});
casper.thenOpen('http://yahoo.fr/', function() {
this.echo("Now I'm in your yahoo.")
});
casper.run();</code></pre>
<p><span class="label label-success">Added in 1.0</span>
You can also specify request settings by passing a <a href="#casper.open">setting object</a> as the second
argument:
</p>
<pre><code class="javascript">casper.start().thenOpen('http://url.to/some/uri', {
method: "post",
data: {
username: 'chuck',
password: 'n0rr15'
}
}, function() {
this.echo("POST request has been sent.")
});
casper.run();</code></pre>
<h3 id="casper.thenOpenAndEvaluate"><code>Casper#thenOpenAndEvaluate(String location[, function then, Object replacements])</code></h3>
<p>Basically a shortcut for opening an url and evaluate code against remote
DOM environment.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://google.fr/').then(function() {
this.echo("I'm in your google.");
});
casper.thenOpenAndEvaluate('http://yahoo.fr/', function() {
var f = document.querySelector('form');
f.querySelector('input[name=q]').value = 'chuck norris';
f.submit();
});
casper.run(function() {
this.debugPage();
this.exit();
});</code></pre>
<h3 id="casper.userAgent"><code>Casper#userAgent(String agent)</code></h3>
<p><span class="label label-success">Added in 1.0</span>
Sets the <a href="http://en.wikipedia.org/wiki/User-Agent">User-Agent string</a> to send
through headers when performing requests.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start();
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X)');
casper.thenOpen('http://google.com/', function() {
this.echo("I'm a Mac.");
});
casper.userAgent('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
casper.thenOpen('http://google.com/', function() {
this.echo("I'm a PC.");
});
casper.run();</code></pre>
<h3 id="casper.viewport"><code>Casper#viewport(Number width, Number height)</code></h3>
<p>Changes current viewport size.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.viewport(1024, 768);</code></pre>
<p><span class="label label-info">Note</span> PhantomJS comes with a default
viewport size of 400x300, and CasperJS doesn't override it by default.
</p>
<h3 id="casper.visible"><code>Casper#visible(String <a href="selectors.html">selector</a>)</code></h3>
<p>Checks if the DOM element matching the provided <a href="selectors.html">selector expression</a> is visible
in remote page.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://google.com/', function() {
if (this.visible('#hplogo')) {
this.echo("I can see the logo");
} else {
this.echo("I can't see the logo");
}
});</code></pre>
<h3 id="casper.wait"><code>Casper#wait(Number timeout[, Function then])</code></h3>
<p>Pause steps suite execution for a given amount of time, and optionally
execute a step on done.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://yoursite.tld/', function() {
this.wait(1000, function() {
this.echo("I've waited for a second.");
});
});
casper.run();</code></pre>
<p>You can also write the same thing like this:
</p>
<pre><code class="javascript">casper.start('http://yoursite.tld/');
casper.wait(1000, function() {
this.echo("I've waited for a second.");
});
casper.run();</code></pre>
<h3 id="casper.waitFor"><code>Casper#waitFor(Function testFx[, Function then, Function onTimeout, Number timeout])</code></h3>
<p>Waits until a function returns true to process any next step.
</p>
<p>You can also set a callback on timeout using the <code>onTimeout</code> argument,
and set the timeout using the <code>timeout</code> one, in milliseconds. The
default timeout is set to 5000ms.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://yoursite.tld/');
casper.waitFor(function check() {
return this.evaluate(function() {
return document.querySelectorAll('ul.your-list li').length &gt; 2;
});
}, function then() {
this.captureSelector('yoursitelist.png', 'ul.your-list');
});
casper.run();</code></pre>
<p>Example using the <code>onTimeout</code> callback:
</p>
<pre><code class="javascript">casper.start('http://yoursite.tld/');
casper.waitFor(function check() {
return this.evaluate(function() {
return document.querySelectorAll('ul.your-list li').length &gt; 2;
});
}, function then() { // step to execute when check() is ok
this.captureSelector('yoursitelist.png', 'ul.your-list');
}, function timeout() { // step to execute if check has failed
this.echo("I can't haz my screenshot.").exit();
});
casper.run();</code></pre>
<h3 id="casper.waitForSelector"><code>Casper#waitForSelector(String <a href="selectors.html">selector</a>[, Function then, Function onTimeout, Number timeout])</code></h3>
<p>Waits until an element matching the provided <a href="selectors.html">selector expression</a> exists in
remote DOM to process any next step. Uses
<a href="#casper.waitFor">Casper.waitFor()</a>.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('https://twitter.com/#!/n1k0');
casper.waitForSelector('.tweet-row', function() {
this.captureSelector('twitter.png', 'html');
});
casper.run();</code></pre>
<h3 id="casper.waitWhileSelector"><code>Casper#waitWhileSelector(String <a href="selectors.html">selector</a>[, Function then, Function onTimeout, Number timeout])</code></h3>
<p>Waits until an element matching the provided <a href="selectors.html">selector expression</a> does not
exist in remote DOM to process a next step. Uses
<a href="#casper.waitFor">Casper.waitFor()</a>.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://foo.bar/');
casper.waitWhileSelector('.selector', function() {
this.echo('.selector is no more!');
});
casper.run();</code></pre>
<h3 id="casper.waitForResource"><code>Casper#waitForResource(Function testFx[, Function then, Function onTimeout, Number timeout])</code></h3>
<p>Wait until a resource that matches the given <code>testFx</code> is loaded to
process a next step. Uses <a href="#casper.waitFor">Casper.waitFor()</a>.
</p>
<p><strong>Example:</strong>
</p>
<pre><code class="javascript">casper.start('http://foo.bar/', function() {
this.waitForResource("foobar.png");
});
casper.then(function() {
this.echo('foobar.png has been loaded.');
});
casper.run();</code></pre>
<p>Another way to write the exact same behavior:
</p>
<pre><code class="javascript">casper.start('http://foo.bar/');
casper.waitForResource("foobar.png", function() {
this.echo('foobar.png has been loaded.');
});
casper.run();</code></pre>
<h3 id="casper.waitUntilVisible"><code>Casper#waitUntilVisible(String <a href="selectors.html">selector</a>[, Function then, Function onTimeout, Number timeout])</code></h3>
<p>Waits until an element matching the provided <a href="selectors.html">selector expression</a> is visible in
the remote DOM to process a next step. Uses
<a href="#casper.waitFor">Casper.waitFor()</a>.
</p>
<h3 id="casper.waitWhileVisible"><code>Casper#waitWhileVisible(String <a href="selectors.html">selector</a>[, Function then, Function onTimeout, Number timeout])</code></h3>
<p>Waits until an element matching the provided <a href="selectors.html">selector expression</a> is no longer
visible in remote DOM to process a next step. Uses
<a href="#casper.waitFor">Casper.waitFor()</a>.
</p>
<h3 id="casper.warn"><code>Casper#warn(String message)</code></h3>
<p>Logs and prints a warning message to the standard output.
</p>
<pre><code class="javascript">casper.warn("I'm a warning message.");</code></pre>
<h3 id="casper.zoom"><code>Casper#zoom(Number factor)</code></h3>
<p><span class="label label-success">Added in 1.0</span>
<span class="label label-info">PhantomJS &gt;= 1.6</span>
Sets the current page zoom factor.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start().zoom(2).thenOpen('http://google.com', function() {
this.capture('big-google.png');
});
casper.run();</code></pre>
</div>
<div class="span3 apitoc">
<div class="wrapper api-toc"><h3>Quick reference</h3>
<h4>The <code>Casper</code> class</h4>
<ul>
<li><a href="#casper.options"><code>options</code></a></li>
<li><a href="#casper.back"><code>back()</code></a></li>
<li><a href="#casper.base64encode"><code>base64encode()</code></a></li>
<li><a href="#casper.click"><code>click()</code></a></li>
<li><a href="#casper.clickLabel"><code>clickLabel()</code></a></li>
<li><a href="#casper.capture"><code>capture()</code></a></li>
<li><a href="#casper.captureBase64"><code>captureBase64()</code></a></li>
<li><a href="#casper.captureSelector"><code>captureSelector()</code></a></li>
<li><a href="#casper.clear"><code>clear()</code></a></li>
<li><a href="#casper.debugHTML"><code>debugHTML()</code></a></li>
<li><a href="#casper.debugPage"><code>debugPage()</code></a></li>
<li><a href="#casper.die"><code>die()</code></a></li>
<li><a href="#casper.download"><code>download()</code></a></li>
<li><a href="#casper.each"><code>each()</code></a></li>
<li><a href="#casper.echo"><code>echo()</code></a></li>
<li><a href="#casper.evaluate"><code>evaluate()</code></a></li>
<li><a href="#casper.evaluateOrDie"><code>evaluateOrDie()</code></a></li>
<li><a href="#casper.exists"><code>exists()</code></a></li>
<li><a href="#casper.exit"><code>exit()</code></a></li>
<li><a href="#casper.fetchText"><code>fetchText()</code></a></li>
<li><a href="#casper.forward"><code>forward()</code></a></li>
<li><a href="#casper.log"><code>log()</code></a></li>
<li><a href="#casper.fill"><code>fill()</code></a></li>
<li><a href="#casper.getCurrentUrl"><code>getCurrentUrl()</code></a></li>
<li><a href="#casper.getElementAttribute"><code>getElementAttribute()</code></a></li>
<li><a href="#casper.getElementBounds"><code>getElementBounds()</code></a></li>
<li><a href="#casper.getGlobal"><code>getGlobal()</code></a></li>
<li><a href="#casper.getPageContent"><code>getPageContent()</code></a></li>
<li><a href="#casper.getTitle"><code>getTitle()</code></a></li>
<li><a href="#casper.mouseEvent"><code>mouseEvent()</code></a></li>
<li><a href="#casper.open"><code>open()</code></a></li>
<li><a href="#casper.reload"><code>reload()</code></a></li>
<li><a href="#casper.repeat"><code>repeat()</code></a></li>
<li><a href="#casper.resourceExists"><code>resourceExists()</code></a></li>
<li><a href="#casper.run"><code>run()</code></a></li>
<li><a href="#casper.setHttpAuth"><code>setHttpAuth()</code></a></li>
<li><a href="#casper.start"><code>start()</code></a></li>
<li><a href="#casper.then"><code>then()</code></a></li>
<li><a href="#casper.thenEvaluate"><code>thenEvaluate()</code></a></li>
<li><a href="#casper.thenOpen"><code>thenOpen()</code></a></li>
<li><a href="#casper.thenOpenAndEvaluate"><code>thenOpenAndEvaluate()</code></a></li>
<li><a href="#casper.userAgent"><code>userAgent()</code></a></li>
<li><a href="#casper.viewport"><code>viewport()</code></a></li>
<li><a href="#casper.visible"><code>visible()</code></a></li>
<li><a href="#casper.wait"><code>wait()</code></a></li>
<li><a href="#casper.waitFor"><code>waitFor()</code></a></li>
<li><a href="#casper.waitForSelector"><code>waitForSelector()</code></a></li>
<li><a href="#casper.waitWhileSelector"><code>waitWhileSelector()</code></a></li>
<li><a href="#casper.waitForResource"><code>waitForResource()</code></a></li>
<li><a href="#casper.waitUntilVisible"><code>waitUntilVisible()</code></a></li>
<li><a href="#casper.waitWhileVisible"><code>waitWhileVisible()</code></a></li>
<li><a href="#casper.warn"><code>warn()</code></a></li>
<li><a href="#casper.zoom"><code>zoom()</code></a></li>
</ul>
</div>
</div>
</div>
</section>
<section id="client-utils">
<div class="page-header">
<h1>
<span class="section-title">Client-side utils</span>
</h1>
</div>
<div class="row">
<div class="span9 client-utils-content"><p>Casper ships with a few client-side utilities which are injected in the
remote DOM environment, and accessible from there through the
<code>__utils__</code> object instance of the <code>ClientUtils</code> class of the
<code>clientutils</code> module.
</p>
<p><span class="label label-info">Note</span> These tools are provided to avoid
coupling CasperJS to any third-party library like jQuery, Mootools or
something; but you can always include these and have them available client-side
using the <code>Casper.options.clientScripts</code> option.
</p>
<h2 id="bookmarklet">Bookmarklet</h2>
<p>A bookmarklet is also available to help injecting Casper's client-side
utilities in the DOM of your favorite browser.
</p>
<p>Just drag this link
<span class="label label-info"><a href="javascript:(function(){void(function(){if(!document.getElementById('CasperUtils')){var%20CasperUtils=document.createElement('script');CasperUtils.id='CasperUtils';CasperUtils.src='https://raw.github.com/n1k0/casperjs/master/modules/clientutils.js';document.documentElement.appendChild(CasperUtils);var%20interval=setInterval(function(){if(typeof%20ClientUtils==='function'){window.__utils__=new%20window.ClientUtils();clearInterval(interval);}},50);}}());})();">CasperJS utils</a></span>
onto your favorites toobar; when clicking, a <code>__utils__</code> object will
be available within the console of your browser.
</p>
<p><span class="label label-info">Note</span> CasperJS and PhantomJS being based
on Webkit, you're strongly encouraged to use a recent Webkit compatible browser
to use this bookmarklet (Chrome, Safari, etc…)
</p>
<h3 id="clientutils.encode"><code>ClientUtils#encode(String contents)</code></h3>
<p>Encodes a string using the <a href="http://en.wikipedia.org/wiki/Base64">base64
algorithm</a>. For the records,
CasperJS doesn't use builtin <code>window.btoa()</code> function because it can't
deal efficiently with strings encoded using &gt;8b characters.
</p>
<pre><code class="javascript">var base64;
casper.start('http://foo.bar/', function() {
base64 = this.evaluate(function() {
return __utils__.encode("I've been a bit cryptic recently");
});
});
casper.run(function() {
this.echo(base64).exit();
});</code></pre>
<h3 id="clientutils.exists"><code>ClientUtils#exists(String selector)</code></h3>
<p>Checks if a DOM element matching a given <a href="selectors.html">selector expression</a> exists.
</p>
<pre><code class="javascript">var exists;
casper.start('http://foo.bar/', function() {
exists = this.evaluate(function() {
return __utils__.exists('#some_id');
});
});
casper.run(function() {
this.echo(exists).exit();
});</code></pre>
<h3 id="clientutils.findAll"><code>ClientUtils#findAll(String selector)</code></h3>
<p>Retrieves all DOM elements matching a given <a href="selectors.html">selector expression</a>.
</p>
<pre><code class="javascript">var links;
casper.start('http://foo.bar/', function() {
links = this.evaluate(function() {
var elements = __utils__.findAll('a.menu');
return Array.prototype.forEach.call(elements, function(e) {
return e.getAttribute('href');
});
});
});
casper.run(function() {
this.echo(JSON.stringify(links)).exit();
});</code></pre>
<h3 id="clientutils.findOne"><code>ClientUtils#findOne(String selector)</code></h3>
<p>Retrieves a single DOM element by a <a href="selectors.html">selector expression</a>.
</p>
<pre><code class="javascript">var href;
casper.start('http://foo.bar/', function() {
href = this.evaluate(function() {
return __utils__.findOne('#my_id').getAttribute('href');
});
});
casper.run(function() {
this.echo(href).exit();
});</code></pre>
<h3 id="clientutils.getBase64"><code>ClientUtils#getBase64(String url[, String method, Object data])</code></h3>
<p>This method will retrieved a base64 encoded version of any resource
behind an url. For example, let's imagine we want to retrieve the base64
representation of some website's logo:
</p>
<pre><code class="javascript">var logo = null;
casper.start('http://foo.bar/', function() {
logo = this.evaluate(function() {
var imgUrl = document.querySelector('img.logo').getAttribute('src');
return __utils__.getBase64(imgUrl);
});
});
casper.run(function() {
this.echo(logo).exit();
});</code></pre>
<h3 id="clientutils.getBinary"><code>ClientUtils#getBinary(String url[, String method, Object data])</code></h3>
<p>This method will retrieved the raw contents of a given binary resource;
unfortunately though, PhantomJS cannot process these data directly so
you'll have to process them within the remote DOM environment. If you
intend to download the resource, use
<a href="#clientutils.getBase64">ClientUtils.getBase64()</a> or
<a href="api.html#casper.base64encode">Casper.base64encode()</a> instead.
</p>
<pre><code class="javascript">casper.start('http://foo.bar/', function() {
this.evaluate(function() {
var imgUrl = document.querySelector('img.logo').getAttribute('src');
console.log(__utils__.getBinary(imgUrl));
});
});
casper.run();</code></pre>
<h3 id="clientutils.getDocumentHeight"><code>ClientUtils#getDocumentHeight()</code></h3>
<p><span class="label label-success">Added in 1.0</span>
Retrieves current document height.
</p>
<pre><code class="javascript">var documentHeight;
casper.start('http://google.com/', function() {
documentHeight = this.evaluate(function() {
return __utils__.getDocumentHeight();
});
this.echo('Document height is ' + documentHeight + 'px');
});
casper.run();</code></pre>
<h3 id="clientutils.getElementBounds"><code>Casper#getElementBounds(String <a href="selectors.html">selector</a>)</code></h3>
<p>Retrieves boundaries for a DOM element matching the provided
<a href="selectors.html">selector</a>.
</p>
<p>It returns an Object with four keys: <code>top</code>, <code>left</code>, <code>width</code> and <code>height</code>, or
<code>null</code> if the selector doesn't exist.
</p>
<h3 id="clientutils.getElementByXPath"><code>ClientUtils#getElementByXPath(String expression)</code></h3>
<p>Retrieves a single DOM element matching a given <a href="http://www.w3.org/TR/xpath/">XPath expression</a>.
</p>
<h3 id="clientutils.getElementsByXPath"><code>ClientUtils#getElementsByXPath(String expression)</code></h3>
<p>Retrieves all DOM elements matching a given <a href="http://www.w3.org/TR/xpath/">XPath expression</a>, if any.
</p>
<h3 id="clientutils.mouseEvent"><code>ClientUtils#mouseEvent(String type, String selector)</code></h3>
<p>Dispatches a mouse event to the DOM element behind the provided selector.
</p>
<p>Supported events are <code>mouseup</code>, <code>mousedown</code>, <code>click</code>, <code>mousemove</code>, <code>mouseover</code> and <code>mouseout</code>.
</p>
<h3 id="clientutils.removeElementsByXPath"><code>ClientUtils#removeElementsByXPath(String expression)</code></h3>
<p>Removes all DOM elements matching a given <a href="http://www.w3.org/TR/xpath/">XPath expression</a>.
</p>
<h3 id="clientutils.visible"><code>ClientUtils#visible(String selector)</code></h3>
<p>Checks if an element is visible.
</p>
<pre><code class="javascript">var logoIsVisible = casper.evaluate(function() {
return __utils__.visible('h1');
});</code></pre>
</div>
<div class="span3 apitoc">
<div class="wrapper client-utils-toc"><h3>Quick reference</h3>
<h4>The <code>ClientUtils</code> class</h4>
<ul>
<li><a href="#clientutils.encode"><code>encode()</code></a></li>
<li><a href="#clientutils.exists"><code>exists()</code></a></li>
<li><a href="#clientutils.findAll"><code>findAll()</code></a></li>
<li><a href="#clientutils.findOne"><code>findOne()</code></a></li>
<li><a href="#clientutils.getBase64"><code>getBase64()</code></a></li>
<li><a href="#clientutils.getBinary"><code>getBinary()</code></a></li>
<li><a href="#clientutils.getDocumentHeight"><code>getDocumentHeight()</code></a></li>
<li><a href="#clientutils.getElementBounds"><code>getElementBounds()</code></a></li>
<li><a href="#clientutils.getElementByXPath"><code>getElementByXPath()</code></a></li>
<li><a href="#clientutils.getElementsByXPath"><code>getElementsByXPath()</code></a></li>
<li><a href="#clientutils.mouseEvent"><code>mouseEvent()</code></a></li>
<li><a href="#clientutils.removeElementsByXPath"><code>removeElementsByXPath()</code></a></li>
<li><a href="#clientutils.visible"><code>visible()</code></a></li>
</ul>
</div>
</div>
</div>
</section>
<section id="colorizer">
<div class="page-header">
<h1>
<span class="section-title">Colorizer</span>
</h1>
</div>
<div class="row">
<div class="span9 colorizer-content"><p>Casper ships with a <code>colorizer</code> module which contains a <code>Colorizer</code>
class which can print stuff to the console output in color:
</p>
<pre><code class="javascript">var colorizer = require('colorizer').create('Colorizer');
console.log(colorizer.colorize("Hello World", "INFO"));</code></pre>
<p>Though most of the times you will use it transparently using the
<a href="api.html#echo"><code>Casper.echo()</code></a> method:
</p>
<pre><code class="javascript">casper.echo('an informative message', 'INFO'); // printed in green
casper.echo('an error message', 'ERROR'); // printed in red</code></pre>
<h3 id="colorizer.Dummy">Skipping CasperJS styling operations</h3>
<p>If you wish to skip the whole coloration operation and get uncolored plain text, just set the
<code>colorizerType</code> casper option to <code>Dummy</code>:
</p>
<pre><code class="javascript">var casper = require('casper').create({
colorizerType: 'Dummy'
});
casper.echo("Hello", "INFO");</code></pre>
<p><span class="label label-info">Note</span>
That's especially useful if you're using CasperJS on the Windows platform, as there's no support
for colored output on this platform.
</p>
<h3 id="colorizer.styles">Available predefined styles</h3>
<p>Available predefined styles are:
</p>
<ul>
<li><code>ERROR</code>: white text on red background</li>
<li><code>INFO</code>: green text</li>
<li><code>TRACE</code>: green text</li>
<li><code>PARAMETER</code>: cyan text</li>
<li><code>COMMENT</code>: yellow text</li>
<li><code>WARNING</code>: red text</li>
<li><code>GREEN_BAR</code>: green text on white background</li>
<li><code>RED_BAR</code>: white text on red background</li>
<li><code>INFO_BAR</code>: cyan text</li>
</ul>
<p>Here's a sample output of what it can look like:
</p>
<p><img src="images/colorizer.png" alt="capture">
</p>
<h3 id="colorizer.colorize"><code>Colorizer#colorize(String text, String styleName)</code></h3>
<p>Computes a colored version of the provided text string using a given
predefined style.
</p>
<pre><code class="javascript">var colorizer = require('colorizer').create();
console.log(colorizer.colorize("I'm a red error", "ERROR"));</code></pre>
<p><span class="label label-info">Note</span>
Most of the time you won't have to use a <code>Colorizer</code> instance directly as CasperJS provides all the
necessary methods.
</p>
<p>See the list of the <a href="#colorizer.styles">predefined styles available</a>.
</p>
<h3 id="colorizer.format"><code>Colorizer#format(String text, Object style)</code></h3>
<p>Formats a text string using the provided style definition. A style
definition is a standard javascript <code>Object</code> instance which can define
the following properties:
</p>
<ul>
<li>String <code>bg</code>: background color name</li>
<li>String <code>fg</code>: foreground color name</li>
<li>Boolean <code>bold</code>: apply bold formatting</li>
<li>Boolean <code>underscore</code>: apply underline formatting</li>
<li>Boolean <code>blink</code>: apply blink formatting</li>
<li>Boolean <code>reverse</code>: apply reverse formatting</li>
<li>Boolean <code>conceal</code>: apply conceal formatting</li>
</ul>
<p><span class="label label-info">Note</span> Available color names are <code>black</code>,
<code>red</code>, <code>green</code>, <code>yellow</code>, <code>blue</code>, <code>magenta</code>, <code>cyan</code> and <code>white</code>.
</p>
<pre><code class="javascript">var colorizer = require('colorizer').create();
colorizer.format("We all live in a yellow submarine", {
bg: 'yellow',
fg: 'blue',
bold: true
});</code></pre>
</div>
<div class="span3 apitoc">
<div class="wrapper colorizer-toc"><h3>Quick reference</h3>
<h4>The <code>Colorizer</code> class</h4>
<ul>
<li><a href="#colorizer.colorize"><code>colorize()</code></a></li>
<li><a href="#colorizer.format"><code>format()</code></a></li>
</ul>
</div>
</div>
</div>
</section>
<section id="tester">
<div class="page-header">
<h1>
<span class="section-title">Tester</span>
</h1>
</div>
<div class="row">
<div class="span9 tester-content"><p>Casper ships with a <code>tester</code> module and a <code>Tester</code> class providing an
API for unit &amp; functional testing purpose. By default you can access an
instance of this class through the <code>test</code> property of any <code>Casper</code> class
instance.
</p>
<p><span class="label label-info">Note</span> The best way to learn how to use the
Tester API and see it in action is probably to have a look at the <a href="https://github.com/n1k0/casperjs/blob/master/tests/run.js">CasperJS
test suite code</a>.
</p>
<h3 id="tester.assert"><code>Tester#assert(Boolean condition[, String message])</code></h3>
<p>Asserts that the provided condition strictly resolves to a boolean
<code>true</code>.
</p>
<pre><code class="javascript">var url = 'http://www.google.fr/';
var casper = require('casper').create();
casper.start(url, function() {
this.test.assert(this.getCurrentUrl() === url, 'url is the one expected');
});</code></pre>
<h3 id="tester.assertDoesntExist"><code>Tester#assertDoesntExist(String selector[, String message])</code></h3>
<p>Asserts that an element matching the provided
<a href="selectors.html">selector expression</a> doesn't exists within the remote DOM
environment.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertDoesntExist('form[name="gs"]', 'google.fr has a form with name "gs"');
});</code></pre>
<h3 id="tester.assertEquals"><code>Tester#assertEquals(mixed testValue, mixed expected[, String message])</code></h3>
<p>Asserts that two values are strictly equals.
</p>
<pre><code class="javascript">var url = 'http://www.google.fr/';
var casper = require('casper').create();
casper.start(url, function() {
this.test.assertEquals(this.getCurrentUrl(), url, 'url is the one expected');
});</code></pre>
<h3 id="tester.assertEval"><code>Tester#assertEval(Function fn[, String message])</code></h3>
<p>Asserts that a <a href="api.html#casper.evaluate">code evaluation in remote DOM</a>
resolves to a boolean <code>true</code>.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertEval(function() {
return document.querySelectorAll('form').length &gt; 0;
}, 'google.fr has at least one form');
});</code></pre>
<h3 id="tester.assertEvalEquals"><code>Tester#assertEvalEquals(Function fn, mixed expected[, String message])</code></h3>
<p>Asserts that the result of a
<a href="api.html#casper.evaluate">code evaluation in remote DOM</a> equals to the
expected value.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertEvalEquals(function() {
return document.querySelectorAll('form').length;
}, 1, 'google.fr provides a single form tag');
});</code></pre>
<h3 id="tester.assertExists"><code>Tester#assertExists(String selector[, String message])</code></h3>
<p>Asserts that an element matching the provided <a href="selectors.html">selector expression</a> exists in
remote DOM environment.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertExists('form[name="gs"]', 'google.fr has a form with name "gs"');
});</code></pre>
<h3 id="tester.assertField"><code>Tester#assertField(String input_name, String expected_value[, String message])</code></h3>
<p>Asserts that a given input field has the provided value.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.fill('form[name="gs"]', { q: 'plop' }, false);
this.test.assertField('form[name="gs"] input[name="q"]', 'plop');
});</code></pre>
<h3 id="tester.assertHttpStatus"><code>Tester#assertHttpStatus(Number status[, String message])</code></h3>
<p>Asserts that current <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP status code</a>
is the same as the one passed as argument.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertHttpStatus(200, 'google.fr is up');
});</code></pre>
<h3 id="tester.assertMatch"><code>Tester#assertMatch(mixed subject, RegExp pattern[, String message])</code></h3>
<p>Asserts that a provided string matches a provided javascript <code>RegExp</code>
pattern.
</p>
<pre><code class="javascript">casper.test.assertMatch('Chuck Norris', /^chuck/i, 'Chuck Norris' first name is Chuck');</code></pre>
<h3 id="tester.assertNot"><code>Tester#assertNot(mixed subject[, String message])</code></h3>
<p>Asserts that the passed subject resolves to some
<a href="http://11heavens.com/falsy-and-truthy-in-javascript">falsy value</a>.
</p>
<pre><code class="javascript">casper.test.assertNot(false, "Universe is still operational");</code></pre>
<h3 id="tester.assertNotEquals"><code>Tester#assertNotEquals(mixed testValue, mixed expected[, String message])</code></h3>
<p><span class="label label-success">Added in 0.6.7</span>
Asserts that two values are <strong>not</strong> strictly equals.
</p>
<pre><code class="javascript">casper.test.assertNotEquals(true, "Truth is out");</code></pre>
<h3 id="tester.assertNotVisible"><code>Tester#assertNotVisible(String selector[, String message])</code></h3>
<p>Asserts that the element matching the provided <a href="selectors.html">selector expression</a> is not visible.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertNotVisible('h6');
});</code></pre>
<h3 id="tester.assertRaises"><code>Tester#assertRaises(Function fn, Array args[, String message])</code></h3>
<p>Asserts that the provided function called with the given parameters
raises a javascript <code>Error</code>.
</p>
<pre><code class="javascript">casper.test.assertRaises(function(throwIt) {
if (throwIt) {
throw new Error('thrown');
}
}, [true], 'Error has been raised.');
casper.test.assertRaises(function(throwIt) {
if (throwIt) {
throw new Error('thrown');
}
}, [false], 'Error has been raised.'); // fails</code></pre>
<h3 id="tester.assertSelectorDoesntHaveText"><code>Tester#assertSelectorDoesntHaveText(String selector, String text[, String message])</code></h3>
<p>Asserts that given text does not exist in the provided <a href="selectors.html">selector</a>.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertSelectorDoesntHaveText('title', 'Yahoo!');
});</code></pre>
<h3 id="tester.assertSelectorExists"><code>Tester#assertSelectorExists(String selector[, String message])</code></h3>
<p>Asserts that at least an element matching the provided <a href="selectors.html">selector expression</a>
exists in remote DOM.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertSelectorExists('form[name="gs"]', 'google.fr provides a form');
});</code></pre>
<h3 id="tester.assertSelectorHasText"><code>Tester#assertSelectorHasText(String selector, String text[, String message])</code></h3>
<p>Asserts that given text exists in the provided <a href="selectors.html">selector</a>.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertSelectorHasText('title', 'Google');
});</code></pre>
<h3 id="tester.assertResourceExists"><code>Tester#assertResourceExists(Function testFx[, String message])</code></h3>
<p>The <code>testFx</code> function is executed against all loaded assets and the test passes
when at least one resource matches.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertResourceExists(function (resource) {
return resource.url.match('logo3w.png');
}, 'google.fr logo was loaded');
// or shorter
this.test.assertResourceExists('logo3w.png', 'google.fr logo was loaded');
});</code></pre>
<p>Check the documentation for <a href="api.html#casper.resourceExists"><code>Casper.resourceExists()</code></a>.
</p>
<h3 id="tester.assertTextExists"><code>Tester#assertTextExists(String expected[, String message])</code></h3>
<p>Asserts that body <strong>plain text content</strong> contains the given string.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertTextExists('google', 'page body contains "google"');
});</code></pre>
<h3 id="tester.assertTitle"><code>Tester#assertTitle(String expected[, String message])</code></h3>
<p>Asserts that title of the remote page equals to the expected one.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertTitle('Google', 'google.fr has the correct title');
});</code></pre>
<h3 id="tester.assertTitleMatch"><code>Tester#assertTitleMatch(RegExp pattern[, String message])</code></h3>
<p>Asserts that title of the remote page matches the provided RegExp pattern.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertTitleMatch(/Google/, 'google.fr has a quite predictable title');
});</code></pre>
<h3 id="tester.assertType"><code>Tester#assertType(mixed input, String type[, String message])</code></h3>
<p>Asserts that the provided input is of the given type.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.test.assertType(42, "number", "Okay, 42 is a number");
casper.test.assertType([1, 2, 3], "array", "Yeah, we can test for arrays too =)");</code></pre>
<h3 id="tester.assertUrlMatch"><code>Tester#assertUrlMatch(Regexp pattern[, String message])</code></h3>
<p>Asserts that a the current page url matches the provided RegExp pattern.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertUrlMatch(/^http:\/\//', 'google.fr is served in http://');
});</code></pre>
<h3 id="tester.assertVisible"><code>Tester#assertVisible(String selector[, String message])</code></h3>
<p>Asserts that the element matching the provided
<a href="selectors.html">selector expression</a> is visible.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.start('http://www.google.fr/', function() {
this.test.assertVisible('h1');
});</code></pre>
<h3 id="tester.colorize"><code>Tester#colorize(String message, String style)</code></h3>
<p>Render a colorized output. Basically a proxy method for
<code>Casper.Colorizer#colorize()</code>.
</p>
<h3 id="tester.comment"><code>Tester#comment(String message)</code></h3>
<p>Writes a comment-style formatted message to stdout.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.test.comment("Hi, I'm a comment");</code></pre>
<h3 id="tester.error"><code>Tester#error(String message)</code></h3>
<p>Writes an error-style formatted message to stdout.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.test.error("Hi, I'm an error");</code></pre>
<h3 id="tester.fail"><code>Tester#fail(String message)</code></h3>
<p>Adds a failed test entry to the stack.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.test.fail("Georges W. Bush");</code></pre>
<h3 id="tester.formatMessage"><code>Tester#formatMessage(String message, String style)</code></h3>
<p>Formats a message to highlight some parts of it. Only used internally by
the tester.
</p>
<h3 id="tester.getFailures"><code>Tester#getFailures()</code></h3>
<p><span class="label label-success">Added in 1.0</span>
Retrieves failures for current test suite.
</p>
<pre><code class="javascript">casper.test.assertEquals(true, false);
require('utils').dump(casper.test.getFailures());
casper.test.done();</code></pre>
<p>That will give something like this:
</p>
<pre><code>$ casperjs test test-getFailures.js
Test file: test-getFailures.js
FAIL Subject equals the expected value
# type: assertEquals
# subject: true
# expected: false
{
"length": 1,
"cases": [
{
"success": false,
"type": "assertEquals",
"standard": "Subject equals the expected value",
"file": "test-getFailures.js",
"values": {
"subject": true,
"expected": false
}
}
]
}
FAIL 1 tests executed, 0 passed, 1 failed.
Details for the 1 failed test:
In c.js:0
assertEquals: Subject equals the expected value</code></pre>
<h3 id="tester.getPasses"><code>Tester#getPasses()</code></h3>
<p><span class="label label-success">Added in 1.0</span>
Retrieves a report for successful test cases in the current test suite.
</p>
<pre><code class="javascript">casper.test.assertEquals(true, true);
require('utils').dump(casper.test.getPasses());
casper.test.done();</code></pre>
<p>That will give something like this:
</p>
<pre><code>$ casperjs test test-getPasses.js
Test file: test-getPasses.js
PASS Subject equals the expected value
{
"length": 1,
"cases": [
{
"success": true,
"type": "assertEquals",
"standard": "Subject equals the expected value",
"file": "test-getPasses.js",
"values": {
"subject": true,
"expected": true
}
}
]
}
PASS 1 tests executed, 1 passed, 0 failed.</code></pre>
<h3 id="tester.info"><code>Tester#info(String message)</code></h3>
<p>Writes an info-style formatted message to stdout.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.test.info("Hi, I'm an informative message.");</code></pre>
<h3 id="tester.pass"><code>Tester#pass(String message)</code></h3>
<p>Adds a successful test entry to the stack.
</p>
<pre><code class="javascript">var casper = require('casper').create();
casper.test.pass("Barrack Obama");</code></pre>
<h3 id="tester.renderResults"><code>Tester#renderResults(Boolean exit, Number status, String save)</code></h3>
<p>Render tests results, save results in an XUnit formatted file, and optionally
exit phantomjs.
</p>
<pre><code class="javascript">var casper = require('casper').create();
// ...
casper.run(function() {
// exists with status code 0 and saves XUnit formatted results
// in test-results.xml
this.test.renderResults(true, 0, 'test-results.xml');
});</code></pre>
</div>
<div class="span3 apitoc">
<div class="wrapper tester-toc"><h3>Quick reference</h3>
<h4>The <code>Tester</code> class</h4>
<ul>
<li><a href="#tester.assert"><code>assert()</code></a></li>
<li><a href="#tester.assertDoesntExist"><code>assertDoesntExist()</code></a></li>
<li><a href="#tester.assertEquals"><code>assertEquals()</code></a></li>
<li><a href="#tester.assertEval"><code>assertEval()</code></a></li>
<li><a href="#tester.assertEvalEquals"><code>assertEvalEquals()</code></a></li>
<li><a href="#tester.assertExists"><code>assertExists()</code></a></li>
<li><a href="#tester.assertField"><code>assertField()</code></a></li>
<li><a href="#tester.assertHttpStatus"><code>assertHttpStatus()</code></a></li>
<li><a href="#tester.assertMatch"><code>assertMatch()</code></a></li>
<li><a href="#tester.assertNot"><code>assertNot()</code></a></li>
<li><a href="#tester.assertNotEquals"><code>assertNotEquals()</code></a></li>
<li><a href="#tester.assertNotVisible"><code>assertNotVisible()</code></a></li>
<li><a href="#tester.assertRaises"><code>assertRaises()</code></a></li>
<li><a href="#tester.assertResourceExists"><code>assertResourceExists()</code></a></li>
<li><a href="#tester.assertSelectorDoesntHaveText"><code>assertSelectorDoesntHaveText()</code></a></li>
<li><a href="#tester.assertSelectorExists"><code>assertSelectorExists()</code></a></li>
<li><a href="#tester.assertSelectorHasText"><code>assertSelectorHasText()</code></a></li>
<li><a href="#tester.assertTextExists"><code>assertTextExists()</code></a></li>
<li><a href="#tester.assertTitle"><code>assertTitle()</code></a></li>
<li><a href="#tester.assertTitleMatch"><code>assertTitleMatch()</code></a></li>
<li><a href="#tester.assertType"><code>assertType()</code></a></li>
<li><a href="#tester.assertUrlMatch"><code>assertUrlMatch()</code></a></li>
<li><a href="#tester.assertVisible"><code>assertVisible()</code></a></li>
<li><a href="#tester.colorize"><code>colorize()</code></a></li>
<li><a href="#tester.comment"><code>comment()</code></a></li>
<li><a href="#tester.error"><code>error()</code></a></li>
<li><a href="#tester.fail"><code>fail()</code></a></li>
<li><a href="#tester.formatMessage"><code>formatMessage()</code></a></li>
<li><a href="#tester.getFailures"><code>getFailures()</code></a></li>
<li><a href="#tester.getPasses"><code>getPasses()</code></a></li>
<li><a href="#tester.info"><code>info()</code></a></li>
<li><a href="#tester.pass"><code>pass()</code></a></li>
<li><a href="#tester.renderResults"><code>renderResults()</code></a></li>
</ul>
</div>
</div>
</div>
</section>
<section id="utils">
<div class="page-header">
<h1>
<span class="section-title">Utils</span>
</h1>
</div>
<div class="row">
<div class="span9 utils-content"><p>The <code>utils</code> module contains simple functions which circumvent some lacks in the
standard Javascript API.
</p>
<p>Usage is pretty much straightforward:
</p>
<pre><code class="javascript">var utils = require('utils');
utils.dump({plop: 42});</code></pre>
<h3 id="utils.betterTypeOf"><code>utils.betterTypeOf(input)</code></h3>
<p>Provides a better <code>typeof</code> operator equivalent, able to retrieve the <code>Array</code>
type.
</p>
<h3 id="utils.dump"><code>utils.dump(value)</code></h3>
<p>Dumps a JSON representation od passed argument onto the standard output. Useful
for <a href="debugging.html">debugging</a>.
</p>
<h3 id="utils.fileExt"><code>utils.fileExt(file)</code></h3>
<p>Retrieves the extension of passed filename.
</p>
<h3 id="utils.fillBlanks"><code>utils.fillBlanks(text, pad)</code></h3>
<p>Fills a string with trailing spaces to match <code>pad</code> length.
</p>
<h3 id="utils.format"><code>utils.format(f)</code></h3>
<p>Formats a string against passed args. <code>sprintf</code> equivalent.
</p>
<p><span class="label label-info">Note</span>
This is a port of nodejs <code>util.format()</code>.
</p>
<h3 id="utils.getPropertyPath"><code>utils.getPropertyPath(Object obj, String path)</code></h3>
<p><span class="label label-success">Added in 1.0</span>
Retrieves the value of an Object foreign property using a dot-separated
path string:
</p>
<pre><code class="javascript">var account = {
username: 'chuck',
skills: {
kick: {
roundhouse: true
}
}
}
utils.getPropertyPath(account, 'skills.kick.roundhouse'); // true</code></pre>
<p><strong>Beware, this function doesn't handle object key names containing a dot.</strong>
</p>
<h3 id="utils.inherits"><code>utils.inherits(ctor, superCtor)</code></h3>
<p>Makes a constructor inheriting from another. Useful for subclassing and
<a href="extending.html">extending</a>.
</p>
<p><span class="label label-info">Note</span>
This is a port of nodejs <code>util.inherits()</code>.
</p>
<h3 id="utils.isArray"><code>utils.isArray(value)</code></h3>
<p>Checks if passed argument is an instance of <code>Array</code>.
</p>
<h3 id="utils.isCasperObject"><code>utils.isCasperObject(value)</code></h3>
<p>Checks if passed argument is an instance of <code>Casper</code>.
</p>
<h3 id="utils.isClipRect"><code>utils.isClipRect(value)</code></h3>
<p>Checks if passed argument is a <code>cliprect</code> object.
</p>
<h3 id="utils.isFunction"><code>utils.isFunction(value)</code></h3>
<p>Checks if passed argument is a function.
</p>
<h3 id="utils.isJsFile"><code>utils.isJsFile(file)</code></h3>
<p>Checks if passed filename is a Javascript one (by checking if it has a <code>.js</code> or
<code>.coffee</code> file extension).
</p>
<h3 id="utils.isNull"><code>utils.isNull(value)</code></h3>
<p>Checks if passed argument is a <code>null</code>.
</p>
<h3 id="utils.isNumber"><code>utils.isNumber(value)</code></h3>
<p>Checks if passed argument is an instance of <code>Number</code>.
</p>
<h3 id="utils.isObject"><code>utils.isObject(value)</code></h3>
<p>Checks if passed argument is an object.
</p>
<h3 id="utils.isString"><code>utils.isString(value)</code></h3>
<p>Checks if passed argument is an instance of <code>String</code>.
</p>
<h3 id="utils.isType"><code>utils.isType(what, type)</code></h3>
<p>Checks if passed argument has its type matching the <code>type</code> argument.
</p>
<h3 id="utils.isUndefined"><code>utils.isUndefined(value)</code></h3>
<p>Checks if passed argument is <code>undefined</code>.
</p>
<h3 id="utils.isWebPage"><code>utils.isWebPage(what)</code></h3>
<p>Checks if passed argument is an instance of native PhantomJS' <code>WebPage</code> object.
</p>
<h3 id="utils.mergeObjects"><code>utils.mergeObjects(origin, add)</code></h3>
<p>Merges two objects recursively.
</p>
<h3 id="utils.node"><code>utils.node(name, attributes)</code></h3>
<p>Creates an (HT|X)ML element, having optional <code>attributes</code> added.
</p>
<h3 id="utils.serialize"><code>utils.serialize(value)</code></h3>
<p>Serializes a value using JSON format. Will serialize functions as strings.
Useful for <a href="debugging.html">debugging</a> and comparing objects.
</p>
<h3 id="utils.unique"><code>utils.unique(array)</code></h3>
<p>Retrieves unique values from within a given <code>Array</code>.
</p>
</div>
<div class="span3 apitoc">
<div class="wrapper utils-toc"><h3>Quick reference</h3>
<h4>The <code>utils</code> module</h4>
<ul>
<li><a href="#utils.betterTypeOf"><code>betterTypeOf()</code></a></li>
<li><a href="#utils.dump"><code>dump()</code></a></li>
<li><a href="#utils.fileExt"><code>fileExt()</code></a></li>
<li><a href="#utils.fillBlanks"><code>fillBlanks()</code></a></li>
<li><a href="#utils.format"><code>format()</code></a></li>
<li><a href="#utils.getPropertyPath"><code>getPropertyPath()</code></a></li>
<li><a href="#utils.inherits"><code>inherits()</code></a></li>
<li><a href="#utils.isArray"><code>isArray()</code></a></li>
<li><a href="#utils.isCasperObject"><code>isCasperObject()</code></a></li>
<li><a href="#utils.isClipRect"><code>isClipRect()</code></a></li>
<li><a href="#utils.isFunction"><code>isFunction()</code></a></li>
<li><a href="#utils.isJsFile"><code>isJsFile()</code></a></li>
<li><a href="#utils.isNull"><code>isNull()</code></a></li>
<li><a href="#utils.isNumber"><code>isNumber()</code></a></li>
<li><a href="#utils.isObject"><code>isObject()</code></a></li>
<li><a href="#utils.isString"><code>isString()</code></a></li>
<li><a href="#utils.isType"><code>isType()</code></a></li>
<li><a href="#utils.isUndefined"><code>isUndefined()</code></a></li>
<li><a href="#utils.isWebPage"><code>isWebPage()</code></a></li>
<li><a href="#utils.mergeObjects"><code>mergeObjects()</code></a></li>
<li><a href="#utils.node"><code>node()</code></a></li>
<li><a href="#utils.serialize"><code>serialize()</code></a></li>
<li><a href="#utils.unique"><code>unique()</code></a></li>
</ul>
</div>
</div>
</div>
</section>
</div>
<footer>
<hr>
<p>
© 2011-2012 <a href="https://nicolas.perriault.net/">Nicolas Perriault</a> — get
the source code on GitHub: <a href="http://github.com/n1k0/casperjs">n1k0/casperjs</a> —
logo by <a href="http://www.forveillejeremy.com/">Jeremy Forveille</a> -
<a href="https://plus.google.com/106641872690063476159" rel="publisher">Google+</a> -
<a href="http://flattr.com/thing/586241/CasperJS-a-navigation-scripting-and-testing-utility-for-PhantomJS" class="flattr" target="_blank"><img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0"></a>
</p>
</footer>
</div>
<script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script><script type="text/javascript" async="" src="https://apis.google.com/js/plusone.js"></script><script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script><script type="text/javascript" async="" src="https://apis.google.com/js/plusone.js"></script><script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script><script type="text/javascript" async="" src="https://apis.google.com/js/plusone.js"></script><script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script><script type="text/javascript" async="" src="https://apis.google.com/js/plusone.js"></script><script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script><script type="text/javascript" async="" src="https://apis.google.com/js/plusone.js"></script><script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script><script type="text/javascript" async="" src="https://apis.google.com/js/plusone.js"></script><script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script><script type="text/javascript" async="" src="https://apis.google.com/js/plusone.js"></script><script src="https://apis.google.com/_/apps-static/_/js/gapi/plusone/rt=j/ver=RRQ8vjRTKkw.fr./sv=1/am=!xL2k5pXR5VKYYD8n2w/d=1/rs=AItRSTOeeOd8fvVEblmi9Tys-lRNCczIjQ/cb=gapi.loaded_0" async=""></script><script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"></script><script type="text/javascript" async="" src="https://apis.google.com/js/plusone.js" gapi_processed="true"></script><script type="text/javascript" src="js/jquery.min.js?1348471995809"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js?1348471995809"></script>
<script type="text/javascript" src="prettify/prettify.js?1348471995809"></script>
<script type="text/javascript" src="js/application.js?1348471995809"></script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-71239-7']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body></html>
Jump to Line
Something went wrong with that request. Please try again.