Ishank Jain
Ishank Jain

Reputation: 309

Why the statement inside setInterval function is not getting executed in Phantomjs?

I am trying to Login into website using Phantomjs. When I click loginButton after filling form elements, I was trying to find some element id inside setInterval function as I want page to load first (gave 2 seconds) and then only search for the element but the problem here is : The statements inside my setInterval are not getting executed. Here is the phantomjs code :

var url = "http://www.someUrl.com";
var page = require('webpage').create();

page.onConsoleMessage = function(msg, lineNo, sourceId){
    console.log('console: ' + msg);
};

page.onLoadFinished = function(status){
    console.log("Loading finished");
    page.render('webpage.png');
};

page.open(url, function(status){
    page.evaluate(function(){
        arr = document.getElementsByClassName('formLabel');
        if (typeof arr !== 'undefined'){
            arr[0].value = 'Login-id';
            arr[1].value = 'Password';
        }
        document.getElementById('loginButton').click();
        setInterval(function(){
            console.log("Downloading the file");
            document.getElementById('downloadButton').click();
        }, 2000);
    });
});

When I execute the above code, I get the output as :-

Loading finished
Loading finished

For debugging purposes, I wrote console.log('Downloading the file') inside the setInterval function but this statement is not getting executed. I also render the webpage as image page.render('webpage.png') to check whether I am able to successfully login or not. And I see that Login is successful. So, I have few questions here :-

  1. Why those statements inside setInterval function are not getting executed?
  2. Where should I write those statements to make them work correctly?

In fact, when I wrote those statements just after the loginButton.click() statement, I got this error - TypeError: 'null' is not an object (near 'downloadButton').click();...'), that means page did not load by that time. Hence, I wrote them inside setInterval function and gave the waiting time as 2 seconds.

PS : There is no problem in my click statement because my loginButton.click is working.

Thanks in Advance.

Upvotes: 0

Views: 1196

Answers (1)

rendes
rendes

Reputation: 117

I had run into the same problem when I started experimenting with PhantomJS. I realized that the issue could be that the page.evaluate() is running in the context of the opened page. So when you click on the login button, the page is redirected, so the statements after the click() are not being executed or the output is not visible anymore.

I solved this by creating an another page.run() block and running it after the previous one is finished (ie. in a timeout) - because I wanted to execute that part of the script after the login.

Upvotes: 1

Related Questions