Monday, April 11, 2016

Examples of submitting login-forms using CasperJS

One of the standard use-cases of CasperJS is automation of a user logging in to a webpage.

The login-system requires CasperJS to handle:

- Filling in the username and password field
- Submitting the login-form
- Storing cookies received by the server - This is carried out automatically by CasperJS
- Resending cookies after every new HTTP-request( automatically carried out by CasperJS)

Example 1: Using this.sendKeys:



var casper = require('casper').create({
    pageSettings: {
        loadImages: false,//The script is faster when this field is set to false
        loadPlugins: false,
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
    }
});
  var x = require('casper').selectXPath;
casper.start(url-loginpage, function() {
this.sendKeys("#name_username_form_element", "username");
this.sendKeys("#name_password_form_element", "password");
});
// proceed to click submit using XPATH-expression
casper.thenClick(x(' INSERT XPATH EXPRESSION HERE'));
casper.wait(2000,function() {
casper.capture('screenpicture.png');
}),   // wait some time for page to load and take screenshot

casper.run();


XPATH-expression is easily found inspecting the login form with tools such as Chrome-developer
tool or the Firebug extension in Mozilla Firefox.

Note that sometimes it may work to skip the XPATH expression and instead use:
 
casper.then(function() {
this.clickLabel('TITLE-Login_Button');
});
 
Example 2 : Using casper.fill
 
The syntax is then :
 
 
 
casper.fill('selector', {
    'nameOfFormElement' : 'yourInput'
}, submit);
 
 
 
 
An example form with selector form#loginform and elements username and password is then filled out as follows:
 casper.fill('form#signInForm', {
    'username' : 'mynamehere',
    'password' : 'difficultpasswordhere'
}, true);
 
 
 
In the above expression the submit button is set to true, so it will automatically submit the credentials.

Sometimes it may not work due to some serverside setting. Then at first try to set to 'false' above
and use the .click() method afterwards, i.e add:
 
 
casper.then(function(){
        this.click("selector-signin-button");
    });