How to configure Poltergeist or PhantomJS to not follow redirects?

吃可爱长大的小学妹 提交于 2019-12-04 01:40:58

问题


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

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