简体   繁体   English

等待Casper.js中的URL更改?

[英]Wait for URL change in Casper.js?

There is a waitForUrl() functionality in Casper.js , but is it possible to waitForUrlChange() in Casper.js ? 有一个waitForUrl()在功能Casper.js ,但有可能waitForUrlChange()Casper.js

I mean detecting a change in this.getCurrentUrl() value. 我的意思是检测this.getCurrentUrl()值的变化。 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 这是它的文档: 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. 但是,正如Artjom B.所提到的,这不会涵盖函数扩展将处理的所有情况。 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). 这是一个正确的函数扩展,因为它具有与其他wait*函数相同的语义(参数是可选的并且它等待)​​并且它支持构建器模式(也被某些人称为promise模式)。

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: 正如Darren Cook所提到的,可以通过检查waitForUrlChange是否已存在waitForUrlChange并使用动态参数列表来确定CasperJS何时更改其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;
    };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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