2016-04-16 82 views
0

我是Phantomjs和JavaScript本身的新手,但出於某種原因,我得到的錯誤是即使我聲明變量用戶名並且它是全局變量也無法找到。無法找到變量

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

回答

1

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

評估了網頁的背景下,給定函數。執行被沙盒[...]

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

思考page.evaluate()作爲在遠程位置的黑盒子中的。它對你的腳本一無所知,除了那些你明確指出的傳遞給它外,沒有任何變量。方法如下:

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