简体   繁体   中英

Wait for URL change in Casper.js?

There is a waitForUrl() functionality in Casper.js , but is it possible to waitForUrlChange() in Casper.js ?

I mean detecting a change in this.getCurrentUrl() value. I can't predict the new url value. It can be anything.

There's an event handler for it

casper.on('url.changed',function(url) {
casper.echo(url);
});

Here's the documentation for it: http://casperjs.readthedocs.org/en/latest/events-filters.html#url-changed

However, as Artjom B. mentioned, this won't cover all cases that a function extension would handle. It's only really appropriate when you don't need it as part of the control flow, but just want to reactively scrape some values when it happens.

Not built in, but you can write your own pretty easy:

casper.waitForUrlChange = function(then, onTimeout, timeout){
    var oldUrl;
    this.then(function(){
        oldUrl = this.getCurrentUrl();
    }).waitFor(function check(){
        return oldUrl === this.getCurrentUrl();
    }, then, onTimeout, timeout);
    return this;
};

This is a proper function extension, because it has the same semantics as the other wait* functions (arguments are optional and it waits) and it supports the builder pattern (also called promise pattern by some).

As mentioned by Darren Cook, one could improve this further by checking whether waitForUrlChange already exists in CasperJS and using a dynamic arguments list for when CasperJS changes its API:

if (!casper.waitForUrlChange) {
    casper.waitForUrlChange = function(){
        var oldUrl;
        // add the check function to the beginning of the arguments...
        Array.prototype.unshift.call(arguments, function check(){
            return oldUrl === this.getCurrentUrl();
        });
        this.then(function(){
            oldUrl = this.getCurrentUrl();
        });
        this.waitFor.apply(this, arguments);
        return this;
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM