从DOM上下文调用casperjs捕获(求值)

Call casperjs capture from DOM context (evaluate)

本文关键字:求值 捕获 casperjs DOM 上下文 调用      更新时间:2023-09-26

是否有任何方法可以调用casperjs方法,如捕获,当函数从评估上下文调用?

解释:我希望能够编写js脚本(qunit),可以在"真正的"浏览器或casper中运行。

样本:

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

我尝试了闭包,但失败了:

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

我知道有一种方法可以使用console.log作为消息总线,但我正在寻找更好的解决方案。

谢谢

在PhantomJS(以及CasperJS)中,evaluate运行在一个被监禁的环境中。只接受原始对象,即可以通过JSON.stringifyJSON.parse序列化的对象。

通常的做法是从主脚本运行屏幕截图。您仍然可以从其他地方触发捕获,包括在evaluate中,您只需要将其通信回主脚本。查看PhantomJS包含的run-qunit.js示例,该示例通过监视特定DOM元素的存在来检测测试的完成情况。

没有办法在evaluate()中运行casper方法。这里是你的代码,修正:

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