本文介绍了如何从casper.evaluate()设置变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从casper.evaluate()中设置一个值,稍后将对其进行检查以进行测试,但这似乎不起作用.

I'm trying to set a value from within casper.evaluate() that I will check later to run a test on, but it doesn't seem to be working.

isArticleOrReview = false;
casper.waitFor(function check() { //here I'm just waiting for jQuery to load
    return this.evaluate(function() {
        return jQuery.fn.jquery == '1.2.6';
    });
}, function then() { //once jQuery has been loaded, do this stuff
    this.evaluate(function() {
        isArticleOrReview =  (jQuery('body').hasClass('node-type-review') || jQuery('body').hasClass('node-type-article'));
        __utils__.echo('isArticleOrReview ' + isArticleOrReview);
    });
});
casper.then(function(){
    casper.test.info('isArticleOrReview ' + isArticleOrReview);
});

对于输出,我得到:

isArticleOrReview true
isArticleOrReview false

我希望它读为:

isArticleOrReview true
isArticleOrReview true

推荐答案

evaluate被沙箱化.所评估的函数无法访问周围的代码,周围的代码也无法访问所评估的功能.这是来自PhantomJS的一个简单示例(Casper的evaluate在下面使用该示例):

evaluate is sandboxed. The evaluated function has no access to the surrounding code, nor does surrounding code have access to the evaluated function. Here is a simpler example from PhantomJS (Casper's evaluate uses that underneath):

var page = require('webpage').create();
page.open('http://google.com/', function(status) {
  var titleVar = "NOT SET";

  var titleReturn = page.evaluate(function() {
    // This would result in an error:
    // console.log('Variable in evaluate:', titleVar);
    // ReferenceError: Can't find variable: titleVar

    titleVar = document.title;
    return document.title;
  });

  console.log('Return value from evaluate:', titleReturn);
  console.log('Variable post evaluate:', titleVar);
  phantom.exit();
});

如您所知,它将打印

Return value from evaluate: Google
Variable post evaluate: NOT SET

,如果取消注释evaluate内的console.log行,则会看到evaluate崩溃并烧毁,因为该变量不存在.

and if you uncomment the console.log line inside evaluate, you will see evaluate crash and burn, since the variable does not exist.

因此,您只能通过evaluate参数传递值并返回值(并且只能是JSON可序列化的值):

Thus, you can only pass values through evaluate parameters and return values (and only those that are JSON-serialisable):

isArticleOrReview = this.evaluate(function() {
  return (jQuery('body').hasClass('node-type-review') || jQuery('body').hasClass('node-type-article'));
});

这篇关于如何从casper.evaluate()设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:18