Call casperjs capture from DOM context (evaluate)

Is there any way to call casperjs methods like capture when function is called from evaluate context ?

Explanation : i want to be able to write js scripts (qunit) that can run both in a "real" browser or in casper.

Sample :

function screenshot()(
//i'm runing in a "real" browser ? Then only console.log 
//i'm running in casper ? Then call capser.capture()

I tried this with closure but fails :

var casper = require('casper').create();
casper.start('http://google.fr/');

casper.evaluate(function(o) {
o.capture('/tmp/google.png', {
    top: 100,
    left: 100,
    width: 500,
    height: 400
});
}, {o: this});

casper.run()


TypeError: JSON.stringify cannot serialize cyclic structures.                   
  :/modules/webpage.js:249
  /Users/macbookpro/js:576 in evaluate
  /Users/macbookpro/js/testClosure.js:11

I know there's a way to use use console.log as a message bus but i'm searching for a better solution.

Thanks

Answers


In PhantomJS (and thus also CasperJS), evaluate runs in a jailed environment. Only primitive objects, something you can serialize via JSON.stringify and JSON.parse is accepted.

The usual practice is to run the screen capture from your main script. You can still trigger the capture from other place, including within evaluate, you just need to communicate it back to the main script. Check out PhantomJS included run-qunit.js example which detects the completion of the tests by monitoring the existence of a particular DOM element.


There's no way to run casper methods within evaluate(). Here's your code, fixed:

var casper = require('casper').create();

casper.start('http://google.fr/', function() {
    this.capture('google.png', {
        top: 100,
        left: 100,
        width: 500,
        height: 400
    });
});

casper.run()

Need Your Help

google maps api v3 route changing destination with a known road by itself

google-maps-api-3 routes

How can I prevent directionsService.route from changing my destination, which is in the format of latitude longitude, to the nearest known address? It is strange because in the route that the api d...

When setting http authorization headers the AngularJS app crashes

angularjs angularjs-resource angular-http angularjs-authentication

I want to make a request to the twitter api and get the current logged in userfeed.