简体   繁体   中英

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM