Tim Duncklee Tim Duncklee - 7 months ago 126
Javascript Question

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?

Answer

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