How to configure Poltergeist or PhantomJS to not follow redirects?

99封情书 提交于 2019-12-01 08:11:51

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!