从evaluate方法调用时不显示消息 [英] Message does not appear when called from evaluate method

查看:421
本文介绍了从evaluate方法调用时不显示消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是casperjs的新手并且玩弄它,但我无法使其 evaluate()功能正常工作。

I'm new to casperjs and playing around with it, but I can't get its evaluate() functionality to work.

这是我的例子

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

casper.echo('started...');

casper.start('http://www.google.de/');

casper.then(function() {
    this.echo(this.getTitle());
});

casper.then(function() {
    this.evaluate(function() {
        this.echo('test');
    });
});

casper.run();

我用执行它casperjs sample.js

启动后... Google 控制台输出中没有任何反应不执行evaluate方法中给出的闭包函数。

After started... and Google nothing happens in console output. The closure function given in the evaluate method is not executed.

我甚至没有通过控制台获得进一步的信息 - 详细

I don't even get further informations by console with --verbose.

我做错了什么?

推荐答案

casper.evaluate 回调是页面上下文。它中的所有内容都直接在页面上执行,并且是沙箱。 指的是此回调中的窗口对象。我怀疑google是否添加了 window.echo 功能。所以你不会在控制台中看到任何东西。 this.echo casper.echo 只能在页面上下文之外使用。

Inside of the casper.evaluate callback is the page context. Everything in it executes directly on the page and it is sandboxed. this refers to the window object inside this callback. I doubt that google has added a window.echo function. So you will not see something in the console. this.echo or casper.echo are only usable outside of the page context.

要从页面上下文中实际查看控制台消息,您需要注册 remote.message 事件:

To actually see console messages from the page context you need to register to the remote.message event:

casper.on("remote.message", function(msg){
    this.echo("remote.msg: " + msg);
});

并写一些东西到控制台:

and write something to the console:

this.evaluate(function() {
    console.log('test');
});

如果您已注册 page.error 事件:

If you would have registered to the page.error event:

casper.on("page.error", function(pageErr){
    this.echo("page.err: " + JSON.stringify(pageErr));
});

你会看到, window.echo 无法调用,因为它是 undefined 。调用它会导致TypeError,它会停止执行 evaluate()回调,然后会给你 null 作为 evaluate()执行的结果。

you would have seen, that window.echo cannot be called because it is undefined. Calling it, will result in a TypeError, which stops execution of the evaluate() callback, which then gives you null as the result of the evaluate() execution.

有关 evaluate <的更多信息/ code>查看我的答案此处

注意:尝试在google上编写第一个脚本不是一个好主意,因为你会遇到多个问题。 Google嗅探用户代理,并根据它为您提供不同的网站。此外,还将考虑视口大小。我建议你从example.org开始,然后是stackoverflow.com,因为两者都表现得相当好。

Note: It is not a good idea to try to write your first scripts on google, because you will run into multiple problems. Google sniffs the user-agent and will give you a different site depending on it. Also the viewport size will be taken into account. I would suggest you start with example.org and then stackoverflow.com, because both behave rather well.

这篇关于从evaluate方法调用时不显示消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆