0

I am trying to automate login to a forum ( yet another forum , test forum available here: http://testforum.yetanotherforum.net/ ) using node-phantom.

This is my code:

/**
 * Yet Another Forum Object
 *
 *
 */
var yaf = function() {}; //

module.exports = new yaf();


var phantom = require('node-phantom');

//var sleep = require('sleep');


var configTestForum = {
  loginUrl: "http://testforum.yetanotherforum.net/login",
  loginFormDetail: {
    usernameBox: 'forum_ctl03_Login1_UserName', // dom element ID
    passwordBox: 'forum_ctl03_Login1_Password',
    submitButton: 'forum_ctl03_Login1_LoginButton'
  },
  loginInfo: {
    username: 'testbot',
    password: 'testbot123'
  }
};

var config = configTestForum;


// program logic
yaf.prototype.login = function(username, password, cb) {

  var steps = [];
  var testindex = 0;
  var loadInProgress = false; //This is set to true when a page is still loading

  /*********SETTINGS*********************/


  phantom.create(function(error, ph) {
    ph.createPage(function(err, page) {


      page.set('settings', {
        userAgent: "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0",
        javascriptEnabled: true,
        loadImages: false,
      });

      phantom.cookiesEnabled = true;
      phantom.javascriptEnabled = true;
      /*********SETTINGS END*****************/

      console.log('All settings loaded, start with execution');

      /**********DEFINE STEPS THAT FANTOM SHOULD DO***********************/
      steps = [

        //Step 1 - Open Amazon home page
        function() {
          console.log('Step 1 - Open Login Page');

          page.open(config.loginUrl, function(status) {

          });
        },
        function() {
          console.log('Step 2 - Populate and submit the login form');


          var submitForm = function(config) {

            console.log('Form Submit 1 ( putting login )');
            document.getElementById(config.loginFormDetail.usernameBox).value = config.loginInfo.username;
            console.log('Form Submit 2 ( putting pass )');

            //jQuery('#' + config.loginFormDetail.passwordBox).val(config.loginInfo.password);
            //jQuery('#' + config.loginFormDetail.usernameBox).val(config.loginInfo.password);

            document.getElementById(config.loginFormDetail.passwordBox).value = config.loginInfo.password;
            console.log('Form Submit 3 ( clicking button ) ');
            document.getElementById(config.loginFormDetail.submitButton).click();

            //var clickElement = function (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);
            //    console.log('dispatched!');
            //};

            //document.getElementById(config.loginFormDetail.submitButton).click();
            //clickElement(jQuery("#forum_ctl03_Login1_LoginButton")[0]);

            //
            //var form = document.getElementById('form1');
            ////var list = function(object) {
            ////    for(var key in object) {
            ////        console.log(key);
            ////    }
            ////};
            ////list(form);
            //
            //
            //// jQuery('#form1').submit();
            //
            //form.submit();
            //
            //document.forms[0].submit();

            //HTMLFormElement.prototype.submit.call(jQuery('form')[0]);

            console.log('Form Has Been Submitted <-----------------');
          };

          var subittedForm = function(err, retVal) {
            console.log('Form Submit error : ' + err);
            console.log('Form Submit returned : ' + retVal);
          };


          //page.evaluateJavaScript(jsCode);
          page.evaluate(submitForm, subittedForm, config);


        },
        //Step 3 - wait for submit form to finish loading..
        function() {
          //sleep.sleep(5);
          console.log("Step 3 - wait for submit form to finish loading..");
          //sleep.sleep(3);
          page.render('loginComplete.png');
          page.get('cookies', function(err, cookies) {
            //   console.log(cookies);
          });

          page.evaluate(function() {
            console.log(document.URL);
          });


        },
        function() {
          console.log('Exiting');
        }
      ];
      /**********END STEPS THAT FANTOM SHOULD DO***********************/

      //Execute steps one by one
      interval = setInterval(executeRequestsStepByStep, 500);

      function executeRequestsStepByStep() {
        if (loadInProgress == false && typeof steps[testindex] == "function") {
          //console.log("step " + (testindex + 1));
          steps[testindex]();
          testindex++;
        }
        if (typeof steps[testindex] != "function") {
          console.log("test complete!");
          ph.exit();
          // cb(ph);
          cb('done');
        }
      }


      page.onLoadStarted = function() {
        loadInProgress = true;
        console.log('Loading started');
      };
      page.onLoadFinished = function() {
        loadInProgress = false;
        console.log('Loading finished');
      };
      page.onConsoleMessage = function(msg) {
        console.log(msg);
      };
      page.onError = function(msg, trace) {
        var msgStack = ['ERROR: ' + msg];

        if (trace && trace.length) {
          msgStack.push('TRACE:');
          trace.forEach(function(t) {
            msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function+'")' : ''));
          });
        }

        console.error('\n' + msgStack.join('\n'));
      };
      page.onResourceError = function(resourceError) {
        console.error('Unable to load resource (#' + resourceError.id + ' URL:' + resourceError.url + ')');
        console.error('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
      };
      page.onResourceTimeout = function(msg) {
        console.error('onResourceTimeout!!>' + msg);
      };
      page.onAlert = function(msg) {
        console.error('onAlert!!> ' + msg);
      };


    });
  });


  //  var page = webPage.create();

};

Output of the code is :

Step 1 - Open Login Page
Loading started
Loading finished
Step 2 - Populate and submit the login form
Form Submit 1(putting login)
Form Submit 2(putting pass)
Form Submit 3(clicking button)
Form Has Been Submitted < -----------------
  Form Submit error: null
Form Submit returned: null
Unable to load resource(#14 URL:http://testforum.yetanotherforum.net/login?g= login &= )
Error code: 5.Description: Operation canceled

ERROR: TypeError: 'undefined'
is not an object(evaluating 'Sys.WebForms.Res.PRM_TimeoutError'), [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object]
Step 3 - wait
for submit form to finish loading..
http: //testforum.yetanotherforum.net/login
  Exiting
test complete!
  done
Option client store expiration is not valid.Please refer to the README.

Process finished with exit code 0

What it attempts to do is :

  1. Open login page : http://testforum.yetanotherforum.net/login?returnurl=%2fcategory%2f1-Test-Category
  2. Try to login using login name / password and then clicking the button.
  3. Take a screenshot and Retrieve the cookies ( containing the auth data )

Currently it is getting stuck in step 2. It can populate the login and password box, but no kind of clicking or submitting the form is working.Basically it is stuck as shown:

(as you can see the login / password are filled correctly ).

By looking at step 2 ( Step 2 - Populate and submit the login form ) in my code, do you notice anything obvious? or am I doing something wrong in the page settings?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Shrouk Khan
  • 1,440
  • 6
  • 27
  • 53
  • `click()` is only available on `` and ` – Artjom B. Nov 15 '15 at 11:35
  • the element in question here `document.getElementById(config.loginFormDetail.submitButton).click();` is indeed . Additionally I have also tried document.getElementById('form1').submit() And jQuery('#form1').submit(); . None worked so far ! Interestingly this same piece of code works fine in other sites ! – Shrouk Khan Nov 15 '15 at 13:24
  • Which PhantomJS version do you use? Please register to the `onError`, `onResourceError`, `onResourceTimeout` events ([Example](https://gist.github.com/artjomb/4cf43d16ce50d8674fdf#file-3_phantomnodeerrors-js)). Maybe there are errors. – Artjom B. Nov 15 '15 at 13:29
  • using phantomjs 1.9.0 , also added the onError,onResourceError etc. still no avail. Interestingly, the same js code that works in the chrome developer console does not work in the `page.evaluate(function(){})` block of this page http://testforum.yetanotherforum.net/login?g=login&returnurl=%2f – Shrouk Khan Nov 15 '15 at 14:16
  • PhantomJS 1.9.0 is really old. You might want to upgrade to 2.0.0, 1.9.8 or 1.9.7. Either way, have you tried all solutions from here: http://stackoverflow.com/q/15739263? – Artjom B. Nov 15 '15 at 14:19
  • upgraded to phantom 1.9.8 . Made some progress. Currently getting stuck with resource error: Unable to load resource (#14 URL:http://testforum.yetanotherforum.net/login?g=login&=) Error code: 5. Description: Operation canceled ( the http://testforum.yetanotherforum.net/login?g=login&= url is the post url of the form , so it seems it is indeed trying to post ,, but getting cancelled immediately ) . Any idea? I – Shrouk Khan Nov 15 '15 at 16:00
  • I don't know. The URL that gets cancelled looks funny, because it has spaces. – Artjom B. Nov 15 '15 at 16:26

0 Answers0