Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax calls using JQuery.active, this method is limited to applications built on the JQuery framework. My goal is to create a solution that can monitor and wait for all types of network calls to conclude, not just those specific to Ajax.

My approach involves identifying the current number of ongoing network calls in the background and waiting for this count to reach zero.

This is my proposed strategy, but I am open to any alternative ideas or suggestions on how to handle this challenge.

Answer №1

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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unrecognized error encountered while using Angularjs/Ionic: Property 'then' cannot be read as it is undefined

codes: js: angular.module('starter.services', ['ngResource']) .factory('GetMainMenu',['$http','$q','$cacheFactory',function($http,$q,$cacheFactory) { var methodStr = 'JSONP' ...

Is it possible to use tabs.create to generate a tab and then inject a content script, where the code attribute is effective but the file attribute seems to be ineffective

I am currently facing an issue with injecting a content script file into a newly created tab. The problem lies in the fact that I keep receiving an error stating chrome.tabs.executeScript(...) is undefined in the console output of the Popup. It may be wort ...

Launching a modal in a new browser window with the help of JavaScript or PHP

I need to implement a feature where clicking a link opens a modal in a new tab and redirects the current page to a different link, similar to how retailmenot handles coupons. Here is the code snippet I am currently working with: <div onClick="myFunctio ...

Exploring unescaped XML for handling unicode characters

Currently tackling the challenge of parsing some XML that is not properly formatted. The XML file contains un-escaped ampersands, which goes against the standard rules for XML files. My goal is to extract unicode formatted phrases from this XML file whil ...

Tips for preventing FormLabel components from turning blue when a radio button is selected

Currently, I am working on a Reactjs project that utilizes Material Ui components. In this project, I am tasked with creating a form to generate a new event where users can select the event location type from three options - In-Person, Hybrid, and Virtual ...

The correct method for including a CSS file in a Vue.js application

How can external CSS files be properly added in a Vue.js Application? I have come across multiple methods for adding CSS files in a Vue.js Application. One suggestion is to use the following code: <link rel="stylesheet" type="text/css" href="/static/b ...

Ways to conceal the current state changes from being displayed in the URL

I've implemented a React form with text fields and radio buttons to store data in the state. The 'Proceed' button triggers an onClick function: handleClick(event){ console.log(this.state); var userID = 1; firebase.database().ref ...

Is there a way to retrieve the drop down selection from the Property file using Selenium WebDriver?

Presently engaged in working with Selenium WebDriver and utilizing Java. The reports are being generated within the TestNG framework. Currently scripting for a web application that consists of numerous drop-down menus, each offering multiple options. I hav ...

What is the best way to incorporate AngularJS data into JavaScript for use in Google Chart?

How can I leverage my AngularJS scope data in a Google Chart or JavaScript? Below is my AngularJS file: angular.module('reports').controller('ReportInfoCtrl', ['$scope', 'reports', '$rootScope','$loca ...

typescript - instantiate an object using values stored in an array

Assume we have a model defined as follows. export interface Basicdata { materialnumber: number; type: string; materialclass: string; } We also have an array containing values that correspond directly to the Basicdata model in order, like this: ...

Looking to implement an explicit wait for the 'invisibilityOfElementLocated' condition on a child window handler?

Are you looking to apply an explicit wait for 'invisibilityOfElementLocated' on a child window handler? With the following code, I am able to iterate between window handlers. String parentWindow = driver.getWindowHandle(); Set<String> han ...

What is the best way to create titles with a background?

My goal is to have a title overlay an image with specific width and the text displayed in blocks. To better illustrate, here's an example: I prefer to achieve this effect using CSS; however, I am open to utilizing Javascript if needed. ...

Using DraftJS to swap text while preserving formatting

Currently, I am implementing Draftjs with draft-js-plugins-editor and utilizing two plugins: draft-js-mathjax-plugin and draft-js-mention-plugin My goal is to replace all mentions with their corresponding values when the user uses '@' to mention ...

How can you retrieve an array of multiple property values from a collection of dynamic objects?

I am currently working with a dynamic JavaScript object array that has varying structures. For example: var someJsonArray = [ {point: 100, level: 3}, {point: 100, level: 3}, {point: 300, level: 6} ]; At times, it may have a different combination lik ...

Converting object to string does not yield the desired outcome

I am working with Selenium in Python and I am encountering an issue when trying to convert the result of name = browser.find_element_by_css_selector('elementname') into a string. The output is 'WebElement' instead of the actual eleme ...

Dealing with performance issues in React Recharts when rendering a large amount of data

My Recharts use case involves rendering over 20,000 data points, which is causing a blocking render: https://codesandbox.io/s/recharts-render-blocking-2k1eh?file=/src/App.tsx (Check out the CodeSandbox with a small pulse animation to visualize the blocki ...

Using Javascript to place a form inside a table

When attempting to add a Form inside a Table, only the input tags are being inserted without the form tag itself. $(function () { var table = document.getElementById("transport"); var row = table.insertRow(0); var cell1 = row.insertCell(0); ...

What is the process for enabling text-only mode in Selenium Chrome browser?

I wish my browser could have a clean and image-free interface like this https://i.stack.imgur.com/T3MW1.jpg Just text, no images displayed at all I attempted to achieve this using the following code: options.experimental_options["prefs"] = chr ...

Preserving color output while executing commands in NodeJS

My Grunt task involves shelling out via node to run "composer install". var done = this.async(); var exec = require('child_process').exec; var composer = exec( 'php bin/composer.phar install', function(error, stdout, stderr) { ...

Is there a way to establish communication between two ReactJS components by utilizing Jotai?

I am facing a problem with 2 reactjs files: Reports.js (handles report requests and displays results) AuthContext.js (maintains communication with backend server through a socket connection) The user initially visits the report page generated by Reports. ...