-
Notifications
You must be signed in to change notification settings - Fork 0
API Reference
Applies to: PhantomJS 1.7
Note: This page serves as a reference. To learn step-by-step on how to use PhantomJS, please refer to the Quick Start guide.
Assuming PhantomJS is built and its executable is place somewhere in the PATH, it can be invoked as follows:
phantomjs [options] somescript.js [arg1 [arg2 [...]]]
The script code will be executed as if it running in a web browser with an empty page. Since PhantomJS is headless, there will not be anything visible shown up on the screen.
If PhantomJS is invoked without any argument, it will enter the interactive mode (REPL).
## Command-line Options ## Supported command-line options are: * `--cookies-file=/path/to/cookies.txt` specifies the file name to store the persistent [Cookies](#cookie). * `--disk-cache=[yes|no]` enables disk cache (at desktop services cache storage location, default is `no`). * `--help` or `-h` lists all possible command-line options. _Halts immediately, will not run a script passed as argument._ * `--ignore-ssl-errors=[yes|no]` ignores SSL errors, such as expired or self-signed certificate errors (default is `no`). * `--load-images=[yes|no]` load all inlined images (default is `yes`). * `--local-to-remote-url-access=[yes|no]` allows local content to access remote URL (default is `no`). * `--max-disk-cache-size=size` limits the size of disk cache (in KB). * `--output-encoding=encoding` sets the encoding used for terminal output (default is `utf8`). * `--proxy=address:port` specifies the proxy server to use (e.g. `--proxy=192.168.1.42:8080`). * `--proxy-type=[http|socks5|none]` specifies the type of the proxy server (default is `http`). * `--script-encoding=encoding` sets the encoding used for the starting script (default is `utf8`). * `--version` or `-v` prints out the version of PhantomJS. _Halts immediately, will not run a script passed as argument._ * `--web-security=[yes|no]` disables web security and allows cross-domain XHR (default is `yes`).Alternatively, since PhantomJS 1.3, you can also utilize a JavaScript Object Notation (JSON) configuration file instead of passing in multiple command-line options:
--config=/path/to/config.json
The contents of config.json should be a standalone JavaScript object. Keys are de-dashed, camel-cased equivalents of the other supported command-line options. Values are their JavaScript equivalents: 'yes'/'no' values translate into true/false Boolean values, numbers remain numbers, strings remain strings. For example:
{
/* Same as: --ignore-ssl-errors=yes */
"ignoreSslErrors": true,
/* Same as: --max-disk-cache-size=1000 */
"maxDiskCacheSize": 1000,
/* Same as: --output-encoding=utf8 */
"outputEncoding": "utf8"
/* etc. */
}Example:
phantom.addCookie({
'name': 'Added-Cookie-Name',
'value': 'Added-Cookie-Value',
'domain': '.google.com'
});Example:
phantom.deleteCookie('Added-Cookie-Name');Example:
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function '' + t.function + '')' : ''));
});
}
console.error(msgStack.join('\n'));
};As of PhantomJS 1.7, however, users can reference their own modules from the file system using require as well.
Note: For backward compatibility with legacy PhantomJS applications, the constructor also remains exposed as a deprecated global WebPage object:
var page = new WebPage();Example:
page.clipRect = { top: 14, left: 3, width: 400, height: 300 };Example:
// Send two additional headers 'X-Test' and 'DNT'.
page.customHeaders = {
'X-Test': 'foo',
'DNT': '1'
};Do you only want these customHeaders passed to the initial WebPage#open request? Here's the recommended workaround:
// Send two additional headers 'X-Test' and 'DNT'.
page.customHeaders = {
'X-Test': 'foo',
'DNT': '1'
};
page.onInitialized = function() {
page.customHeaders = {};
};The given object should be in one of the following two formats:
{ width: '200px', height: '300px', border: '0px' }
{ format: 'A4', orientation: 'portrait', border: '1cm' }If no paperSize is defined, the size is defined by the web page. Supported dimension units are: 'mm', 'cm', 'in', 'px'. No unit means 'px'. Border is optional and defaults to 0. Supported formats are: 'A3', 'A4', 'A5', 'Legal', 'Letter', 'Tabloid'. Orientation ('portrait', 'landscape') is optional and defaults to 'portrait'.
Example:
page.paperSize = { width: '5in', height: '7in', border: '20px' };Note: The settings apply only during the initial call to the WebPage#open function. Subsequent modification of the settings object will not have any impact.
Because PhantomJS is headless (nothing is shown), viewportSize effectively simulates the size of the window like in a traditional browser.
Example:
page.viewportSize = { width: 480, height: 800 };Example:
// Create a thumbnail preview with 25% zoom
page.zoomFactor = 0.25;
page.render('capture.png');Example:
page.addCookie({
'name': 'Added-Cookie-Name',
'value': 'Added-Cookie-Value'
});Due to some technical limitations, the web page object might not be completely garbage collected. This is often encountered when the same object is used over and over again. Calling this function may stop the increasing heap allocation.
#### `deleteCookie(cookieName)` {boolean} #### **Introduced:** PhantomJS 1.7 Delete any [Cookies](#cookie) visible to the current URL with a 'name' property matching `cookieName`. Returns `true` if successfully deleted, otherwise `false`.Example:
page.deleteCookie('Added-Cookie-Name');Example:
var page = require('webpage').create();
page.open('http://m.bing.com', function(status) {
var title = page.evaluate(function() {
return document.title;
});
console.log(title);
phantom.exit();
});As of PhantomJS 1.6, JSON-serializable arguments can be passed to the function. In the following example, the text value of a DOM element is extracted. The following example achieves the same end goal as the previous example but the element is chosen based on a selector which is passed to the evaluate call:
var page = require('webpage').create();
page.open('http://m.bing.com', function(status) {
var title = page.evaluate(function(s) {
return document.querySelector(s).innerText;
}, 'title');
console.log(title);
phantom.exit();
});Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine. Closures,
functions, DOM nodes, etc. will not work!
Example:
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function() {
/* jQuery is loaded, now manipulate the DOM */
});Example:
page.open('http://www.google.com/', function(status) {
console.log('Status: ' + status);
// Do other things here...
});Due to some technical limitations, the web page object might not be completely garbage collected. This is often encountered when the same object is used over and over again. Calling this function may stop the increasing heap allocation.
#### `render(filename)` {void} #### Renders the web page to an image buffer and saves it as the specified `filename`.Currently, the output format is automatically set based on the file extension. Supported formats include:
- PNG
- GIF
- JPEG
Supported formats include:
- PNG
- GIF
- JPEG
The events are not like synthetic DOM events. Each event is sent to the web page as if it comes as part of user interaction.
The first argument is the event type. Supported types are 'mouseup', 'mousedown', 'mousemove', 'doubleclick' and 'click'. The next two arguments are optional but represent the mouse position for the event.
The button parameter (defaults to left) specifies the button to push.
For 'mousemove', however, there is no button pressed (i.e. it is not dragging).
The first argument is the event type. The supported types are: keyup, keypress and keydown. The second parameter is a key (from page.event.key), or a string.
This function is used to automate the upload of a file, which is usually handled with a file dialog in a traditional browser. Since there is no dialog in this headless mode, such an upload mechanism is handled via this special function instead.
Example:
page.uploadFile('input[name=image]', '/path/to/some/photo.jpg');Example:
page.onAlert = function(msg) {
console.log('ALERT: ' + msg);
};Although there are many possible use cases for this inversion of control, the primary one so far is to prevent the need for a PhantomJS script to be continually polling for some variable on the web page.
Example:
page.onCallback = function(data) {
console.log('CALLBACK: ' + JSON.stringify(data));
};Example:
page.onClosing = function(closingPage) {
console.log('The page is closing! URL: ' + closingPage.url);
};Example:
page.onConfirm = function(msg) {
console.log('CONFIRM: ' + msg);
return true; // `true` === pressing the "OK" button, `false` === pressing the "Cancel" button
};By default, console messages from the web page are not displayed. Using this callback is a typical way to redirect it.
Example:
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};Example:
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
};Example:
page.onInitialized = function() {
page.evaluate(function() {
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM content has loaded.');
}, false);
});
};Also see WebPage#open for an alternate hook for the onLoadFinished callback.
Example:
page.onLoadFinished = function(status) {
console.log('Status: ' + status);
// Do other things here...
};Example:
page.onLoadStarted = function() {
console.log('Now loading...');
};Example:
page.onNavigationRequested = function(url, type, willNavigate, main) {
console.log('Trying to navigate to: ' + url);
console.log('Caused by: ' + type);
console.log('Will actually navigate: ' + willNavigate);
console.log('Sent from the page's main frame: ' + main);
}Example:
page.onPageCreated = function(newPage) {
console.log('A new child page was created! Its requested URL is not yet available, though.');
// Decorate
newPage.onClosing = function(closingPage) {
console.log('A child page is closing: ' + closingPage.url);
};
};Example:
page.onPrompt = function(msg, defaultVal) {
if (msg === 'What's your name?') {
return 'PhantomJS';
}
return defaultVal;
};Example:
page.onResourceRequested = function(request) {
console.log('Request (#' + request.id + '): ' + JSON.stringify(request));
};If the resource is large and sent by the server in multiple chunks, onResourceReceived will be invoked for every chunk received by PhantomJS.
Example:
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};Example:
page.onUrlChanged = function(targetUrl) {
var currentUrl = page.evaluate(function() {
return window.location.href;
});
console.log('Old URL: ' + currentUrl);
console.log('New URL: ' + targetUrl);
};To start using, you must require a reference to the system module:
var system = require('system');The following example demonstrates the same functionality as the Unix printenv utility or the Windows set command:
var env = require('system').env;
Object.keys(env).forEach(function(key) {
console.log(key + '=' + env[key]);
});The following example prints all of the command-line arguments:
var args = require('system').args;
if (args.length === 1) {
console.log('Try to pass some arguments when invoking this script!');
}
else {
args.forEach(function(arg, i) {
console.log(i + ': ' + arg);
});
}To start using, you must require a reference to the fs module:
var fs = require('fs');Here is a simple example that always gives the same response regardless of the request:
var server = require('webserver').create();
var service = server.listen(8080, function(request, response) {
response.statusCode = 200;
response.write('<html><body>Hello!</body></html>');
response.close();
});For example:
phantom.addCookie({
'name': 'Valid-Cookie-Name', /* required property */
'value': 'Valid-Cookie-Value', /* required property */
'domain': 'localhost', /* required property */
'path': '/foo',
'httponly': true,
'secure': false,
'expires': (new Date()).getTime() + 3600 /* <- expires in 1 hour */
});