There is a small workaround. Therefore, you need to first determine which URL is a redirect. Using resource.received
you will receive a response to the first request containing the URL where it should be redirected. But we can do nothing with this event handler. Therefore, we save the destination URL, which is later identified as redirected.
Now the base browser without a header (PhantomJS or SlimerJS) should be redirected to request a new resource, but now resource.requested
provides us with tools to cancel the request (unfortunately, this is not described in CasperJS). So, the final script looks like this:
var casper = require("casper").create(); var redirectURLs = [], doLog = true; casper.on("resource.requested", function(requestData, networkRequest){ if (doLog) console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData) + "\n"); if (redirectURLs.indexOf(requestData.url) !== -1) { // this is a redirect url networkRequest.abort(); } }); casper.on("resource.received", function(response){ if (doLog) console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response) + "\n"); if (response.status === 301) { // use your status here redirectURLs.push(response.redirectURL); } }); casper.start("https://stackoverflow.com/q/27021176").run(function(){ this.echo("DONE"); this.exit(); });
This is adapted from my answer A: How to set up a Poltergeist or PhantomJS to not follow redirects?
You can do the same as with the associated version of PhantomJS directly in CasperJS by exchanging page
for casper.page
, but CasperJS has several advantages. You can add several handlers to the same events with the note casper.on
, and most of them you can decide whether all resources are processed the same way or the pages just load. That way you can exchange resource.received
for page.resource.received
and resource.requested
for page.resource.requested
.
source share