2

I have recently started learning CasperJS and I am trying to log in to YouTube. Here's my current code:

// XPathSignInButton is predefined
var Username = 'user123';
var Password = 'pass123';

casper.waitForSelector(xPathSignInButton, function() {
    this.thenEvaluate(function() {
        $('#Email').val(Username);
        $('#Passwd').val(Password);
    });
}); 

The code above does not manipulate the input fields (does not write in them), however if I replace thenEvaluate() with this.fillSelectors(), the variables are accessed normally and everything executes fine:

// XPathSignInButton is predefined
// signInFormSelector is predefined
casper.waitForSelector(xPathSignInButton, function() {
    this.fillSelectors(signInFormSelector, {
        'input[name="Email"]': Username,
        'input[name="Passwd"]': Password
    });
});

I first thought that there was a problem with how I called jQuery, but when I replaced the variables with the actual strings like: $('#Email').val('user123'); and $('#Email').val('pass123'); - it worked like a charm.

My question is how do I access variables from within the thenEvaluate() function. Is it at all possible?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Dave Cameron
  • 159
  • 1
  • 3
  • 16
  • 1
    As an aside: you could use `evaluate()` here instead of `thenEvaluate()`. Also, prefer the `fill()` functions over `evaluate()` (it saves you having to do the extra work shown in Artjom's answer, for starters). – Darren Cook Jan 20 '15 at 09:10

1 Answers1

5

Inside of evaluate is the sandboxed page context. You cannot use variables from the outside (and other way around), you have to explicitly pass them:

casper.thenEvaluate(function(username, password) {
    $('#Email').val(username);
    $('#Passwd').val(password);
}, Username, Password);

It's also important to note that (from here):

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.

Closures, functions, DOM nodes, etc. will not work!

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222