Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

javascript - Get count of network calls happening in a web page

So basically I'm trying to design a generic method using selenium, that waits for all the background network calls to finish (Including any Ajax, Angular, API calls). I know there is a way to get number of active ajax using JQuery.active, but that works only when the application is build upon JQuery framework. Moreover, i want something that waits for all the network calls to finish and not something specific to Ajax alone.

So here i'm trying to get the number of network calls that are happening currently in the background and wait for it to be zero.

However, that's my idea of handling it, any new ideas or suggestions are welcomed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an example to wait for no pending Ajax request with Chrome:

from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait
import json


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')

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

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...