0

Consider code from node-phantom:

page.evaluate(function() {
    return document.getElementById('foo').innerHTML;
}).then(function(html){
    console.log(html);
});

The funciton is executed directly in html page, so adding a parameter like that:

someExternalVariable = 'foo';
page.evaluate(function() {
    return document.getElementById(someExternalVariable).innerHTML;
}).then(function(html){
    console.log(html);
});

Leads to undefined someExternalVariable, because opened page does not know anything about someExternalVariable. So how to pass external data to evaluate function in phantomjs-node?

Cherry
  • 31,309
  • 66
  • 224
  • 364

1 Answers1

1

If the variable is serializable you could do it this way

someExternalVariable = 'foo';
page.evaluate(function(id) {
    return document.getElementById(id).innerHTML;
}, someExternalVariable ).then(function(html){
    console.log(html);
})

If it's not (say you want to pass a function with closure) I doubt there is a way to do it. Docs.

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98