CasperJS waitForResource: how to get the resource i've waited for

巧了我就是萌 提交于 2019-12-01 10:36:39

问题


casper.test.begin('Test foo', 1, function suite(test) {
    casper.start("http://www.foo.com", function() {
        casper.waitForResource("bar", function(resource) {
            casper.echo(resource.url);
        });
    });

    casper.run(function() {
        test.done();
    });
});

casper.echo returns www.foo.com resource (the one in casper.start), not the one with "bar".

How can I get the resource i've waited for with waitForResource?


回答1:


You actually waited for the "bar" resource. The problem is that resource inside the then callback function of waitForResource is actually the page resource of the last start or open (thenOpen) call. It may also be the current page resource for single page applications.

If you want to wait for the resource and do something based on it, you would have to jump through some hoops:

var res;
casper.waitForResource(function check(resource){
    res = resource;
    return resource.url.indexOf("bar") != -1;
    // or as regular expression:
    //return /bar/.test(resource.url);
}, function(){
    this.echo("Resource found" + res.url);
});

If you don't need to do something for the current flow, you can always do the resource handling in the event handler:

casper.on("resource.received", function(resource){
    if (resource.url.indexOf("bar") != -1) {
        // do something
    }
});
casper.start(url); // ...


来源:https://stackoverflow.com/questions/24559234/casperjs-waitforresource-how-to-get-the-resource-ive-waited-for

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