问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/26809256/how-to-configure-poltergeist-or-phantomjs-to-not-follow-redirects