Wait for URL change in Casper.js?

こ雲淡風輕ζ 提交于 2019-12-10 13:53:42

问题


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.


回答1:


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;
    };
}



回答2:


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.



来源:https://stackoverflow.com/questions/28074458/wait-for-url-change-in-casper-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!