0

I'm new to Phantomjs and JavaScript itself but for some reason I get the error that the variable username can't be found even though I declared it and that it's a global variable.

var page = require('webpage').create();
var system = require("system");

page.open('https://www.facebook.com/login.php?login_attempt/', function(status) {
    page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', function () {        
        var username = "test";
        var password = "test";
        page.evaluate(function () {
            $("#email").val(username);
            $("#pass").val(password);
            $("#loginbutton").click();
        }); 
        page.onLoadFinished = function () { 
            page.render("after_submit.png");
            if (page.url == "https://www.facebook.com/") {
                var fs = require('fs');
                var path = 'succes.txt';
                var content = "Facebook : \n" + username;
                fs.write(path, content, 'w');
            }
            phantom.exit(); 
        };
        page.render("before_submit.png");           
    });
});
Iluvpresident
  • 163
  • 1
  • 15

1 Answers1

1

evaluate
evaluate(function, arg1, arg2, ...) {object}

Evaluates the given function in the context of the web page. The execution is sandboxed [...]

http://phantomjs.org/api/webpage/method/evaluate.html

Think of page.evaluate() as of black box in remote location. It knows nothing of your script, has no variables except for those you specifically pass to it. Here's how:

    var username = "test";
    var password = "test";

    page.evaluate(function (username, password) { // <-- here you receive variables from outside the page
        $("#email").val(username);
        $("#pass").val(password);
        $("#loginbutton").click();
    }, username, password); // <-- here you pass variables to webpage
Vaviloff
  • 16,282
  • 6
  • 48
  • 56