javascript - 等效于 javascript Selenium Web Driver 中的 jQuery.active

标签 javascript jquery selenium selenium-webdriver selenium-firefoxdriver

我正在使用 Selenium webdriver 与某些网站进行交互。
如果网站使用的是 jQuery,我们可以使用 jQuery.active 获取待处理的 AJAX 请求:

 JavascriptExecutor jsx = (JavascriptExecutor) driver;

Int totAjaxRequest = (Int)jsx.executeScript("jQuery.active");

Int totAjaxRequest = (Int)jsx.executeScript("return jQuery.active");

如果网站没有使用 jQuery,我们如何计算 XMLHttpRequest 请求的数量?

最佳答案

这里是一个示例,说明如何使用 nightwatch 自定义命令来完成等待 AJAX 请求。

一个命令来初始化计数器。在每次 send if 时都会增加计数器,并且在每次 open 时都会减少它 customCommands/initAjaxCounters.js:

exports.command = function () {
  this.execute(function () {
    window.sumStartedAjaxRequests = 0
    window.activeAjaxCount = 0

    function isAllXhrComplete () {
      window.activeAjaxCount--
    }

    (function (open) {
      XMLHttpRequest.prototype.open = function () {
        this.addEventListener('loadend', isAllXhrComplete)
        return open.apply(this, arguments)
      }
    })(XMLHttpRequest.prototype.open)
  })
  this.execute(function () {
    (function (send) {
      XMLHttpRequest.prototype.send = function () {
        window.activeAjaxCount++
        window.sumStartedAjaxRequests++
        return send.apply(this, arguments)
      }
    })(XMLHttpRequest.prototype.send)
  })
  return this
}

然后等待另一个自定义命令

const sleepWhenOutstandingAjaxCalls = function (result) {
  if (result.value > 0) {
    this.pause(this.globals.waitForConditionPollInterval)
    this.waitForOutstandingAjaxCalls()
  }
}

exports.command = function () {
  // init the ajax counter if it hasn't been initialized yet
  this.execute('return (typeof window.activeAjaxCount === "undefined")', [], function (result) {
    if (result.value === true) {
      throw Error('checking outstanding Ajax calls will not work without calling initAjaxCounter() first')
    }
  })

  this.execute(
    'return window.activeAjaxCount', [], sleepWhenOutstandingAjaxCalls
  )
  return this
}

关于javascript - 等效于 javascript Selenium Web Driver 中的 jQuery.active,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52514915/

相关文章:

jquery - Foundation 的顶部栏不工作——我做错了什么?

jquery 隐藏或显示图像组

javascript - 使用 javascript 获取 Bootstrap 选项卡的 id

excel - VBA Selenium with Chrome - 将文件上传到网页

javascript - 自动大写 文本框光标自动跳转到末尾

javascript - 如何重置/删除 vuex 存储数据?

JAVA Selenium Webdriver 下载前询问每个文件的保存位置

python - WebDriverException : Service . ..\firefox.exe 通过 Selenium 使用 GeckDriver Firefox 意外退出错误

javascript - 使用 G+ 登录的 Chrome 扩展程序 - redirect_uri_mismatch

javascript - 在 JavaScript 中从变量传递数据