1
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?

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
apelliciari
  • 8,241
  • 9
  • 57
  • 92

1 Answers1

2

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); // ...
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • hi, thanks. I really need only the url that matched my pattern (my first parameter of `waitForResource`). Anyway i'll try if your first solution, i think it will be fine! – apelliciari Jul 04 '14 at 07:29
  • @artjom-b what if i want to save that resource? – j.c Apr 24 '17 at 11:07
  • @j.c Check my answer [here](http://stackoverflow.com/a/24591244/1816580) and the answers to [this question](http://stackoverflow.com/q/11531448/1816580). Maybe some of it helps – Artjom B. Apr 24 '17 at 19:06
  • @ArtjomB. thanx, i already try that solution and didn't work. In my case a PDF is dynamically loaded into an iframe, the only way i was able to save it was intercepting it with pymiproxy as described [here](http://stackoverflow.com/questions/11531448/grab-the-resource-contents-in-casperjs-or-phantomjs#answer-12116959). Thanx anyway. – j.c Apr 26 '17 at 07:13