【问题标题】:How to configure Poltergeist or PhantomJS to not follow redirects?如何配置 Poltergeist 或 PhantomJS 不遵循重定向?
【发布时间】:2014-11-07 20:05:47
【问题描述】:

我有一些测试要求 JS 驱动程序不遵循重定向。是否可以配置 Poltergeist 来做到这一点?

我注意到可以使用Command Line Interface 将命令传递给 PhantomJS,所以这可能是另一种方式吗?

【问题讨论】:

    标签: rspec phantomjs poltergeist


    【解决方案1】:

    我不熟悉Poltergeist,所以我只回答有关PhantomJS的问题。

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

    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);
        }
    };
    

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

    【讨论】:

      猜你喜欢
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      相关资源
      最近更新 更多