phantomjs page.evaluate not logging onto console

user1069596 picture user1069596 · May 22, 2013 · Viewed 20.7k times · Source

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

});

Answer

PP. picture PP. · May 23, 2013

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

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);
};

A more complete implementation would be:

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
  }
);

Outputs:

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

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