Search code examples
javascriptpromisephantomjscasperjs

CasperJS waitForSelector doesn't add "then" to step array


This is how my code looks like:

var firstFrameLoadingTime = 3000;

firstFrameLoadingWaiter(function() {
    casper.echo("callback");
});

function firstFrameLoadingWaiter(callback) {
    casper.waitForSelector('div',
        function suc() {
            casper.echo('success!');
        },
        function timeout() {        
                casper.echo('failure!');
        },
        firstFrameLoadingTime);
}

The problem is that suc function is never called. I mean it's not added to the array of CasperJS steps.

This is a part of the log:

[18] => [info] [phantom] Step _step 5/5 https://... (HTTP 200)
[19] => [info] [phantom] Step _step 5/5: done in 3392ms.
[20] => [info] [phantom] waitFor() finished in 40ms.
[21] => [info] [phantom] Done 5 steps in 3451ms

If selector isn't found on a page before timeout comes script works like a charm.

UPD. As it turned out the problem was in do_while and waitFor incompatibility.


Solution

  • After some time of research I found out that the problem was in do_while modification of step.then function. do_while was incompatible with the waitFor function.

    The workaround (pull request) is simple though not the clearest. I've just named the function in a special way and added a small check:

    var isWaitSuccessFun = step.name.indexOf('successThen') != -1;
    if( isWaitSuccessFun || !this.steps[this.current].executed ) {
    

    To make your waitFor work just ensure the success function name contains successThen as in example:

    casper.waitFor(
        function check(){
            // check if page is ready
        },
        function successThen(){
            // execute after page is ready
        },
        function(){
            // time out happened before page got ready
        },
        timeOutTime
    );
    

    This also makes waitForSelector work as well as other similar functions based on waitFor.

    The full code is available in my forked repository.