Pass arguments with page.evaluate Pass arguments with page.evaluate javascript javascript

Pass arguments with page.evaluate


I've had that exact problem. It can be done with a little trickery, because page.evaluate also can accept a string.

There are several ways to do it, but I use a wrapper called evaluate, which accepts additional parameters to pass to the function that must be evaluated on the webkit side. You would use it like this:

page.open(url, function() {  var foo = 42;  evaluate(page, function(foo) {    // this code has now has access to foo    console.log(foo);  }, foo);});

And here is the evaluate() function:

/* * This function wraps WebPage.evaluate, and offers the possibility to pass * parameters into the webpage function. The PhantomJS issue is here: *  *   http://code.google.com/p/phantomjs/issues/detail?id=132 *  * This is from comment #43. */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);}


The change has been pushed and now you can use it as

page.open(url, function() {  var foo = 42;  page.evaluate( function(foo) {  // this code has now has access to foo  console.log(foo);  }, foo);}

The push details are here: https://github.com/ariya/phantomjs/commit/81794f9096


You can pass in the arguments to the function as arguments to page.evaluate.

Example:

page.evaluate(function(arg1, arg2){    console.log(arg1); //Will print "hi"    console.log(arg2); //Will print "there"}, "hi", "there");