How to wait for visibility in PhantomJS

I found an excellent piece of code on Stack Overflow on how to wait for elements to become visible before performing an action in PhantomJS. I thought I would share it here.

Here is the function required:

function waitFor ($config) {
    $config._start = $config._start || new Date();

    if ($config.timeout && new Date - $config._start > $config.timeout) {
        if ($config.error) $config.error();
        if ($config.debug) console.log('timedout ' + (new Date - $config._start) + 'ms');
        return;
    }

    if ($config.check()) {
        if ($config.debug) console.log('success ' + (new Date - $config._start) + 'ms');
        return $config.success();
    }

    setTimeout(waitFor, $config.interval || 0, $config);
}

Then use the code as follows:

waitFor({
    debug: true,  // optional
    interval: 0,  // optional
    timeout: 1000,  // optional
    check: function () {
        return page.evaluate(function() {
            return $('#thediv').is(':visible');
        });
    },
    success: function () {
        // we have what we want
    },
    error: function () {} // optional
});

Reference

http://stackoverflow.com/questions/16807212/how-to-wait-for-element-visibility-in-phantomjs

Leave a Reply

Your email address will not be published. Required fields are marked *