Tim Duncklee
Tim Duncklee

Reputation: 1420

PhantomJS; If I set a variable inside page.evaluate(), how can I access the value of that variable outside of page.evaluate()

Using PhantomJS consider the following code snippet:

var reloadAfterLogin = false;
function(user, pass, debug){ // step 3 submit Login
   page.evaluate(function(user, pass, debug){
     if($("form").attr("action").indexOf("login.do") > 0){
       reloadAfterLogin = true;
       $('form').submit();
     }
   }, user, pass, debug);
 },

As I understand it, this is more than just a scope issue. The code executing inside of page.evaluate() is a complete separate instance of JavaScript. I have to admit I'm still having a hard time wrapping my head around how PhantomJS works but I need access to the reloadAfterLogin variable outside of page.evaluate(). How can I do this?

Upvotes: 3

Views: 2173

Answers (2)

André
André

Reputation: 2142

If you cannot return from evaluate callbacks as described by Bergi for whatever reason, you can use a hacky workaround by misusing onConsoleMessage:

Send your data as JSON from within webpage.evaluate() like so:

console.log('{"foo": "bar"}');

You can then extract this data to the global space (outside webpage.evaluate()):

webpage.onConsoleMessage = function(msg) {
  var obj = JSON.parse(msg);
  // Do whatever you like with obj...
};

Upvotes: 1

Bergi
Bergi

Reputation: 664528

You can return from the evaluate callbacks. I guess you want

function(user, pass, debug){ // step 3 submit Login
  reloadAfterLogin = page.evaluate(function(user, pass, debug){
    if($("form").attr("action").indexOf("login.do") > 0){
      $('form').submit();
      return true;
    }
    return false;
  }, user, pass, debug);
}

Upvotes: 5

Related Questions