B Seven
B Seven

Reputation: 45943

How to configure Poltergeist or PhantomJS to not follow redirects?

I have some tests that require the JS driver to not follow redirects. Is it possible to configure Poltergeist to do this?

I noticed that it is possible to pass commands to PhantomJS using the Command Line Interface, so perhaps that is another way of doing this?

Upvotes: 4

Views: 1711

Answers (1)

Artjom B.
Artjom B.

Reputation: 61902

I'm not familiar with Poltergeist, so I'm only going to answer about PhantomJS.

All you need for this are the two event handlers page.onResourceRequested and page.onResourceReceived. An HTTP redirect produces both a HTTP request and HTTP response on so the handlers are called when the redirect response is received. You can then add the redirect URL to an array and when the redirect request is actually send, you can detect and stop it.

var redirectURLs = [],
    doLog = true;

page.onResourceRequested = 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();
    }
};

page.onResourceReceived = function(response) {
    if (doLog) console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response) + "\n");
    if (response.status >= 300 && response.status < 400 && response.redirectURL) { // maybe more specific
        redirectURLs.push(response.redirectURL);
    }
};

This only works for HTTP redirects. There are other types of redirects that need other solutions. For example HTML redirects or JavaScript redirects.

Upvotes: 5

Related Questions