最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Wait for URL change in Casper.js? - Stack Overflow

programmeradmin3浏览0评论

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 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.

Share Improve this question asked Jan 21, 2015 at 18:41 Jérôme VerstryngeJérôme Verstrynge 59.6k96 gold badges295 silver badges466 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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/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;
    };
}
发布评论

评论列表(0)

  1. 暂无评论