我正在使用 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/