Skip to content

Instantly share code, notes, and snippets.

@CodeIter
Created July 22, 2016 15:31
Show Gist options
  • Save CodeIter/72a26a3564dfbf6d92be6ff568d87fdf to your computer and use it in GitHub Desktop.
Save CodeIter/72a26a3564dfbf6d92be6ff568d87fdf to your computer and use it in GitHub Desktop.
phantomjs-full-example.js
//phantomjs-full-example.js
var system = require('system');
var fs = require('fs');
var process = require("child_process");
var spawn = process.spawn;
var execFile = process.execFile;
var webPage = require('webpage');
var page = webPage.create();
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
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'));
phantom.exit(1);
}
page.onPrompt = function(msg, defaultVal) {
if (msg === "What's your name?") {
return 'PhantomJS';
}
return defaultVal;
}
page.onAlert = function(msg) {
console.log('ALERT: ' + msg);
}
page.onClosing = function(closingPage) {
console.log('The page is closing! URL: ' + closingPage.url);
}
page.onConfirm = function(msg) {
console.log('CONFIRM: ' + msg);
return true; // `true` === pressing the "OK" button, `false` === pressing the "Cancel" button
}
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
}
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
});
}
console.error(msgStack.join('\n'));
}
page.onFilePicker = function(oldFile) {
if (system.os.name === 'windows') {
return 'C:\\Windows\\System32\\drivers\\etc\\hosts';
}
return '/dev/null';
}
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);
}
}
page.onInitialized = function() {
page.evaluate(function() {
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM content has loaded.');
}, false);
});
}
page.onLoadStarted = function() {
var currentUrl = page.evaluate(function() {
return window.location.href;
});
console.log('Current page ' + currentUrl + ' will gone...');
console.log('Now loading a new page...');
}
page.onLoadFinished = function(status) {
console.log('Status: ' + status);
// Do other things here...
}
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);
}
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
}
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
}
page.onResourceRequested = function(requestData, networkRequest) {
console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
}
page.onResourceTimeout = function(request) {
console.log('Response (#' + request.id + '): ' + JSON.stringify(request));
}
page.onUrlChanged = function(targetUrl) {
console.log('New URL: ' + targetUrl);
}
var postBody = 'user=username&password=password';
page.open('http://www.google.com/', 'POST', postBody, function(status) {
console.log('Status: ' + status);
var wasSuccessful = phantom.injectJs('lib/utils.js');
page.includeJs(
// Include the https version, you can change this to http if you like.
'https://code.jquery.com/jquery-3.1.0.js',
function() {
(page.evaluate(function() {
// jQuery is loaded, now manipulate the DOM
}))
}
);
});
var child = spawn("ls", ["-lF", "/rooot"]);
child.stdout.on("data", function (data) {
console.log("spawnSTDOUT:", JSON.stringify(data))
});
child.stderr.on("data", function (data) {
console.log("spawnSTDERR:", JSON.stringify(data))
});
child.on("exit", function (code) {
console.log("spawnEXIT:", code)
});
//child.kill("SIGKILL")
execFile("ls", ["-lF", "/usr"], null, function (err, stdout, stderr) {
console.log("execFileSTDOUT:", JSON.stringify(stdout))
console.log("execFileSTDERR:", JSON.stringify(stderr))
});
/*http://phantomjs.org/api/fs/method/absolute.html*/
var content;
if (system.os.name === 'windows') {
content = fs.read('C:\\Windows\\System32\\drivers\\etc\\hosts');
}else {
content = fs.read('/dev/null');
}
console.log('read data:', content);
phantom.exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment