Skip to content

Instantly share code, notes, and snippets.

@stefek99
Created February 23, 2013 11:44
Show Gist options
  • Save stefek99/5019469 to your computer and use it in GitHub Desktop.
Save stefek99/5019469 to your computer and use it in GitHub Desktop.
PhantomJS - Performing a series of page interactions. Code from: https://groups.google.com/forum/#!topic/phantomjs/20z8N8rwITw (thanks to respective owners) Opened issue number 1 here: https://github.com/bacey/phasmine/issues/1 (phasmine does not work for me as expected) Usage: put all three files into same directory and phantomjs phantom.js
var pageNum = 1;
function interact (page,callback_list) {
console.log("Setting onLoadFinished");
page.onLoadFinished = function (status) {
// For debugging, log the results and render the page to a temp directory
console.log (status + ":" + pageNum + " Page load complete - " +
page.evaluate(function() {
return document.title + " - " + document.location.href;
})
);
page.render("/tmp/" + pageNum + ".png");
pageNum++;
// Allow elements to be clicked
page.injectJs("simclick.js");
console.log("about to apply callback");
// Call interact again--pass only the functions that
// haven't been invoked yet
interact(page, callback_list.slice(1));
};
// Call the first callback in the list. It should result in page reload so the
// above onLoadFinished gets called
callback_list[0].apply(page);
console.log("Return from interact");
return;
}
phantom.injectJs("interact.js");
page = new WebPage()
var steps = [
function() {
// Open the issues list page
this.open("http://code.google.com/p/phantomjs/issues/list");
},
function() {
// Click on the details link for the last issue on the page
// Would be nice to be able to write:
// click (this, '#resultstable > tbody >tr:nth-last-of-type(1) > td.id > a')
// but I didn't figure out how
this.evaluate(function() {simulateMouseClick('#resultstable > tbody > tr:nth-last-of-type(1) > td.id > a')})
},
function() {
last_update = this.evaluate(function() {
// Creation date or date of most recent comment
n = document.querySelectorAll('.author > .date, .issuecomment > .date');
return n.item(n.length-1).getAttribute('title');
});
console.log ("Last updated " + last_update);
phantom.exit();
}
];
interact(page, steps)
function simulateMouseClick(selector) {
var targets = document.querySelectorAll(selector),
evt = document.createEvent('MouseEvents'),
i, len;
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
for ( i = 0, len = targets.length; i < len; ++i ) {
targets[i].dispatchEvent(evt);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment