PhantomJS runs asynchronously by default, causing problems like the one you describe above (where the script finishes before your results are ready)
However there is nothing to stop you using it in a synchronous way.
Just use phantom.page.sendEvent('mousemove')
in a while loop. This will keep looping through the event pump until the webkit engine loads your page or processes any necessary browser events.
var page = require('webpage').create();
// Step 1: View item
page.open('http://localhost/item3324.php');
do { phantom.page.sendEvent('mousemove'); } while (page.loading);
page.render('step1-viewitem.png');
// Step 2: Add to cart
page.evaluate(function() {$('#add-to-cart').click(); });
do { phantom.page.sendEvent('mousemove'); } while (page.loading);
page.render('step2-viewcart.png');
// Step 3: Confirm contents
page.evaluate(function() {$('#confirm-cart').click(); });
do { phantom.page.sendEvent('mousemove'); } while (page.loading);
page.render('step3-confirm.png');
Note that page.loading
can also be any other boolean condition, for example:
do { phantom.page.sendEvent('mousemove'); }
while (page.evaluate(function() {return $("#panel").is(":visible");}));
I discovered this approach while working on the triflejs.org project (the Internet Explorer version of phantom) trying to emulate calls to trifle.wait(ms)
inside the PhantomJS environment.