Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

controlled async exit from phantomjs

I am trying to do some testing with phantomjs... basically I want to:

  • open a page on my webserver
  • once the page has initialized (all the page js has loaded)
  • call the page js from phantomjs and test the results
  • exit phantomjs

It seems difficult for phantomjs to notice when the page has loaded though.

I could use phantomjs to set a "test" variable on the window or something so that the page js could check that and then call a callback once it's done. The trouble is the callback can only be a page callback, so it can't do anything that a page couldn't do.

That might be ok for the tess but the last step is not possible.

I came up with this:

page.onConsoleMessage = function(msg) {
  if (msg == "__quit__") {
    phantom.exit();
  }
  else {
    console.log("page: " + msg);
  }
};

page.evaluate(function () { 
  window.quit = function () { console.log("__quit__"); };
});

So the page code can call window.quit() and the console monitor can then kill phantom. This seems a bit hacky though. Does anyone have a better way of doing it?

like image 993
nic ferrier Avatar asked Apr 12 '12 14:04

nic ferrier


1 Answers

Disclaimer: this is untested code

You might be able to attach to the onLoadFinished callback of the webpage object. This executes in the scope of PhantomJS so you'll have all your variables available.

Something like this should suffice:

page.onLoadFinished = function(){
   page.evaluate(function() {
//call your testing code here
   });

phantom.exit();
}
like image 95
Thomas Jones Avatar answered Oct 10 '22 03:10

Thomas Jones