Below is a code snippet to ensure there are no pending Ajax requests in Chrome:
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait
import json
# Function to send command to Chrome
def send_chrome(driver, cmd, params={}):
resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
url = driver.command_executor._url + resource
body = json.dumps({'cmd': cmd, 'params': params})
response = driver.command_executor._request('POST', url, body)
if response.get('status'):
raise Exception(response.get('value'))
return response.get('value')
# Extend XHR in Chrome
def extend_xhr_chrome(driver):
send_chrome(driver, "Page.addScriptToEvaluateOnNewDocument", {
"source":
"(function(){"
" var send = XMLHttpRequest.prototype.send;"
" var release = function(){ --XMLHttpRequest.active };"
" var onloadend = function(){ setTimeout(release, 1) };"
" XMLHttpRequest.active = 0;"
" XMLHttpRequest.prototype.send = function() {"
" ++XMLHttpRequest.active;"
" this.addEventListener('loadend', onloadend, true);"
" send.apply(this, arguments);"
" };"
"})();"
})
# Check if XHR is idle in Chrome
def is_xhr_idle_chrome(driver):
return send_chrome(driver, 'Runtime.evaluate', {
'returnByValue': True,
'expression': "XMLHttpRequest.active == 0"
})['result']['value']
# Launch Chrome
driver = webdriver.Chrome()
# Extend XMLHttpRequest
extend_xhr_chrome(driver)
driver.get("https://stackoverflow.com")
# Wait for no pending request
WebDriverWait(driver, 20, 0.08) \
.until(is_xhr_idle_chrome)