phantomjs page.evaluate无法登录控制台 [英] phantomjs page.evaluate not logging onto console

查看:71
本文介绍了phantomjs page.evaluate无法登录控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 PhantomJs 新手.刚刚检查了该网站上的类似帖子.我的问题是为什么"foo"没有登录到控制台或无法打印?

I am a PhantomJs newbie. Just checked a similar post on this site. My question is why 'foo' is not logged to console or printed?

var page = require('webpage').create()
var foo = 42;

function evaluate(page, func) {
    var args = [].slice.call(arguments, 2);
    var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}";
    return page.evaluate(fn);
}

page.open('http://google.com', function() {
  var foo = 42;
  evaluate(page, function(foo) {
  console.log(foo);
        },foo);

});

推荐答案

调用page.evaluate()在沙箱中运行您评估的代码.沙盒的控制台与PhantomJS的控制台不同.

The call page.evaluate() runs your evaluated code in a sandbox. The sandbox's console is not the same as PhantomJS's console.

以下添加到脚本中的行会将页面的控制台打印到stderr.

The following lines added to your script will print your page's console to stderr.

var system = require('system');

page.onConsoleMessage = function(msg) {
    system.stderr.writeLine('console: ' + msg);
};

一个更完整的实现是:

var page = require('webpage').create()
var system = require('system');
var foo = 42;

page.onConsoleMessage = function(msg) {
  system.stderr.writeLine( 'console: ' + msg );
};

function evaluate(page, func) {
  var args = [].slice.call(arguments, 2);
  var fn = "function() { return (" + func.toString() + ").apply(this, " +     JSON.stringify(args) + ");}";
  return page.evaluate(fn);
}

page.open(
  'http://google.com',
  function() {
    var foo = 42;
    evaluate(
      page,
      function(foo) {
        console.log(foo);
      },
      foo
    );

    console.log( "Done" );

    phantom.exit( 0 ); // must exit somewhere in the script
  }
);

输出:

$ phantomjs /tmp/idiot.js 
console: 42
Done

如果您只是想对测试功能进行沙盒测试,则可以使用"about:blank"作为URL来调用page.open.

By the way, you can call page.open using "about:blank" as your URL if you just want to sandbox test the evaluate function.

这篇关于phantomjs page.evaluate无法登录控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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