2013-07-02 71 views
1

我有我的幻影Js代码的问题,如下所示,我有代码来测试我的朋友Web服务器(使用节点Js)。实际上,它看起来很简单,完美运行。使用PhantomJs登录测试

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

var address = "http://localhost:3333"; 

// Route "console.log()" calls from within the Page context to the 
// main Phantom context (i.e. current "this") 
page.onConsoleMessage = function(msg) { 
    console.log("Console.log: ", msg); 
}; 

page.onAlert = function(msg) { 
    console.log("Alert:", msg); 
}; 

page.open(address, function (s) { 
    page.evaluate(function() { 
    function click(el){ 
     var ev = document.createEvent("MouseEvent"); 
     ev.initMouseEvent(
     "click", 
     true /* bubble */, 
     true /* cancelable */, 
     window, null, 
     0, 0, 0, 0, /* coordinates */ 
     false, false, false, false, /* modifier keys */ 
     0 /*left*/, null 
    ); 
     el.dispatchEvent(ev); 
    } 
    document.getElementById('username').value = 'MyName'; 
    document.getElementById('password').value = 'MyWord'; 
    click(document.querySelector('input[type=submit]')); 
    }); 

    page.onNavigationRequested = function() { 
    // console.log("Moved", JSON.stringify(arguments)) 
    // to check whether send or not 
    page.render("printscreen" + ".png"); 
    }; 

    setTimeout(function(){ 
    page.render("nextprintscreen" + ".png"); 
     phantom.exit(); 
    }, 3000); 
}); 

当我宣布
var userName = 'MyName';
var passWord = 'MyWord';
然后将它放在下面
var address = "http://localhost:3333";
和交流
document.getElementById('username').value = 'MyName';
document.getElementById('password').value = 'MyWord';

document.getElementById('username').value = userName;
document.getElementById('password').value = passWord;

它从我的朋友Web服务器返回invalid username or password。你能帮我弄清楚为什么会发生吗?这是我第一个'javascript世界'的代码。

我已经读过this questionanother variation然后a suggestion

,但它只是让我更加迷惑。

感谢,
艾哈迈德

回答

1

问题是page.evaluate()是沙箱,所以有你的幻像脚本变量的访问权限。

由于PhantomJS 1.6,JSON序列化参数可以传递给page.evaluate()。 参数和评估函数的返回值必须是简单基本对象。但是,可以通过JSON序列化一个对象。

您可以更改您的代码如下:

page.evaluate(function (login, pwd) { 
    ... 
    document.getElementById('username').value = login; 
    document.getElementById('password').value = pwd; 
    ... 
}, userName , passWord); 
+0

感谢..我会尝试明天..现在我在休息.. ^^。 –

+0

它像河流一样工作。不管怎么说,还是要谢谢你。 –