You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Karate DSL 1.3.0拦截XHR获取PaymentKeys报错,求解决方案

解决Karate DSL 1.3.0中无法使用driver.intercept()拦截XHR的问题

问题根源

Karate DSL 1.3.0版本并未提供driver.intercept() API,这个方法是在1.4.0及后续版本中才引入的,所以直接调用会抛出Unknown identifier: intercept错误。

解决方案

如果无法升级Karate版本,可通过Chrome DevTools Protocol(CDP)直接与浏览器交互,实现XHR请求拦截和响应数据提取。以下是具体实现代码:

Scenario: 拦截目标XHR并提取PaymentKeys
  Given driver 'chrome'
  And driver.url '你的目标页面URL'
  # 启用Chrome网络监控功能
  * driver.send({ method: 'Network.enable' })
  # 配置请求拦截规则,匹配目标域名的XHR请求
  * driver.send({ 
      method: 'Network.setRequestInterception', 
      params: {
        patterns: [{
          urlPattern: '*hpc.uat.testpay.com*',
          resourceType: 'XHR',
          interceptionStage: 'Response'
        }]
      }
    })
  # 初始化变量存储提取结果
  * def paymentKeys = null
  # 监听响应接收事件,提取PaymentKeys
  * driver.on('Network.responseReceived', function(e) {
      var reqId = e.params.requestId;
      # 获取响应体内容
      driver.send({ method: 'Network.getResponseBody', params: { requestId: reqId } }, function(resp) {
        var body = JSON.parse(resp.result.body);
        paymentKeys = body.PaymentKeys;
      });
      # 放行请求,避免页面阻塞
      driver.send({ method: 'Network.continueInterceptedRequest', params: { requestId: reqId } });
    })
  # 点击按钮触发目标请求
  When driver.click('button:contains("Complete Your Reservation")')
  # 等待结果提取完成(超时10秒)
  * karate.waitUntil(function(){ return paymentKeys != null }, 10000)
  # 验证或使用提取到的PaymentKeys
  Then print '提取到的PaymentKeys:', paymentKeys

注意事项

  • 确保Chrome浏览器版本与Karate内置的ChromeDriver版本兼容,避免出现CDP命令不支持的情况
  • 如果目标响应是压缩格式,需在Network.getResponseBody参数中添加overrideContentType: 'application/json'来处理
  • 若页面存在多个匹配的XHR请求,可通过e.params.response.url进一步过滤目标请求

内容的提问来源于stack exchange,提问作者Jeetendra Edke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:42:53