Skip to content Skip to sidebar Skip to footer

CasperJS Page.resource.request And Page.resource.response Callback Calls Increment When Opening Multiple URL

I've got a small problem which has to do with the following approach: I want to iterate through a given array of URLs with a loop I do this here because I want to measure the load

Solution 1:

casper.on() will always add an event handler to the list. It will not replace them. Since you add the event on every iteration you will get duplicate output from previous iterations.

Additionally, the then callback is called after the URL is loaded, so the event handlers that you register inside of that callback won't be called for the current URL anymore.

casper.start();

/* On every request we take a new start time */
casper.on('page.resource.requested', function(requestData, request) {
    console.log("REQUESTED:",requestData.url);
    s = new Date().getTime();
});

/* And when the response comes in we calculate the difference */
casper.on('page.resource.received', function(response) {
    console.log("RESPONSE DATA GOTTEN: ",response.url);

    var e = new Date().getTime();
    casper.echo("URL: "+url+" - "+"Time between HTTP request and HTTP response : "+ (e-s) + "ms", "INFO");
});

/* Run tests for all given URLs */
casper.each(urls, function(self, url, i) {
    /* Open the next given URL form the array */
    casper.thenOpen(url);
});

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

If you want to make it more robust, then you need to detect if the page was at all loaded. For that you might need to register to "resource.error" and casper.page.onResourceTimeout (Example).


Post a Comment for "CasperJS Page.resource.request And Page.resource.response Callback Calls Increment When Opening Multiple URL"