如何配置 Poltergeist 或 PhantomJS 不跟随重定向? [英] How to configure Poltergeist or PhantomJS to not follow redirects?

查看:18
本文介绍了如何配置 Poltergeist 或 PhantomJS 不跟随重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些测试要求 JS 驱动程序不遵循重定向.是否可以配置 Poltergeist 来执行此操作?

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

我注意到可以使用命令行界面向 PhantomJS 传递命令,所以也许这是另一种方法?

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?

推荐答案

我对 Poltergeist 不熟悉,所以我只回答 PhantomJS.

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

您只需要两个事件处理程序 page.onResourceRequestedpage.onResourceReceived.HTTP 重定向同时生成 HTTP 请求和 HTTP 响应,因此在收到重定向响应时会调用处理程序.然后,您可以将重定向 URL 添加到数组中,当实际发送重定向请求时,您可以检测并阻止它.

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) + "
");
    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) + "
");
    if (response.status >= 300 && response.status < 400 && response.redirectURL) { // maybe more specific
        redirectURLs.push(response.redirectURL);
    }
};

这仅适用于 HTTP 重定向.还有其他类型的重定向需要其他解决方案.例如 HTML 重定向或 JavaScript 重定向.

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

这篇关于如何配置 Poltergeist 或 PhantomJS 不跟随重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆