Lavezzi Lavezzi - 1 month ago 14
Javascript Question

Manipulate http response body in CapserJS

I am using CasperJS 1.1.0-beta3 combined with PhantomJS 1.9.8.

How can i edit the response body content before phantomjs parses and renders it?

Something like:

casper.on("resource.received", function(response) {


You can't do this. PhantomJS does not expose the body, so you cannot change it. There are some tricks when you receive JavaScript, but this cannot be generally applied to any type of resource.

It seems you receive an HTML resource.

It is the page resource

If the HTML resource is the page resource, then you can abort the request using the resource.requested event handler, use __utils__.sendAJAX to retrieve the page source, change the content based on some rules and load it as the current content.

var done = false;
casper.on("page.resource.requested", function(req, network){
    if (req.url === "someUrl") {
        var content = this.evaluate(function(url){
            return __utils__.sendAJAX(url, "GET");
        }, req.url);
        content = content.replace("somehtml", "myhtml");"href=\"/", "href=\"http://domain.tld/path/"), req.url); // fix urls
        done = true;
casper.start(someUrlToManipulate).waitFor(function check(){
    return done;
}, function then(){
    // further processing

It is some other resource

Other resources are usually requested using JavaScript (such as templates). In those cases, you can't do anything, because you would have to reproduce the code that handles such a response.