javascript - 如何从 casper.evaluate() 设置变量?

标签 javascript phantomjs casperjs

我试图在 casper.evaluate() 中设置一个值,稍后我将检查该值以运行测试,但它似乎不起作用。

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 使用下面的示例):

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 崩溃并烧毁,因为该变量不存在.

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

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

关于javascript - 如何从 casper.evaluate() 设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091901/

相关文章:

java - 如何解析 java.net.SocketPermission

javascript - 你需要 python 来使用 casper.js 吗?如果是,为什么?

javascript - 是否可以对已通过 getElementsInfo 检索到的元素使用 getElementsInfo?

javascript - CasperJS 登录表单等待成功

javascript - 为什么当使用 google-maps v3 上的 MVCObject 更改缩放时我的代码无法提醒 map 的缩放

java - Phantom JS 无法找到元素(即使在给出隐式等待 aslo 之后)

javascript - 从 vb.net 代码后面运行 JavaScript

javascript - 使用 R 将字段添加到在线表单并抓取生成的 javascript 创建的表

javascript - 在浏览器中预览本地页面时不调用外部js函数

javascript - 有什么方法可以修改数组中允许的值的标准吗?