Skip to main content
SeleniumDecoded

Wait for Network Idle (No Pending Fetch or XHR)

Wait until the page has no in-flight fetch or XHR requests for a quiet period, using a small injected tracker that works in every browser and binding.

Medium Verified against Selenium 4.52.0

Problem

A dashboard fires a dozen API calls after load and renders widgets as each one returns. There is no single spinner or element that means “done”. document.readyState === 'complete' is true long before the data arrives, and Selenium has no built-in “network idle” wait.

Solution

Inject a tiny tracker that wraps fetch and XMLHttpRequest, counting requests in flight and recording the time of the last activity. Then wait until the count is zero and nothing has happened for a quiet window (500 ms is a good default).

Inject a request tracker, then wait for quiet
Selenium 3 & 4 Medium
private static final String TRACKER = """
if (!window.__net) {
window.__net = { pending: 0, last: Date.now() };
const bump = (d) => { window.__net.pending += d; window.__net.last = Date.now(); };
const origFetch = window.fetch;
window.fetch = function (...args) {
bump(1);
return origFetch.apply(this, args).finally(() => bump(-1));
};
const origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (...args) {
bump(1);
this.addEventListener('loadend', () => bump(-1), { once: true });
return origSend.apply(this, args);
};
}
""";
public static void waitForNetworkIdle(WebDriver driver, Duration timeout, long quietMs) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(TRACKER);
new WebDriverWait(driver, timeout).until(d -> (Boolean) js.executeScript(
"return document.readyState === 'complete' && window.__net.pending === 0 "
+ "&& Date.now() - window.__net.last > arguments[0];", quietMs));
}
driver.get("https://app.example.com/dashboard");
waitForNetworkIdle(driver, Duration.ofSeconds(20), 500);
TRACKER = """
if (!window.__net) {
window.__net = { pending: 0, last: Date.now() };
const bump = (d) => { window.__net.pending += d; window.__net.last = Date.now(); };
const origFetch = window.fetch;
window.fetch = function (...args) {
bump(1);
return origFetch.apply(this, args).finally(() => bump(-1));
};
const origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (...args) {
bump(1);
this.addEventListener('loadend', () => bump(-1), { once: true });
return origSend.apply(this, args);
};
}
"""
IDLE = """
return document.readyState === 'complete' && window.__net.pending === 0
&& Date.now() - window.__net.last > arguments[0];
"""
def wait_for_network_idle(driver, timeout=20, quiet_ms=500):
driver.execute_script(TRACKER)
WebDriverWait(driver, timeout).until(lambda d: d.execute_script(IDLE, quiet_ms))
driver.get("https://app.example.com/dashboard")
wait_for_network_idle(driver)
const TRACKER = `
if (!window.__net) {
window.__net = { pending: 0, last: Date.now() };
const bump = (d) => { window.__net.pending += d; window.__net.last = Date.now(); };
const origFetch = window.fetch;
window.fetch = function (...args) {
bump(1);
return origFetch.apply(this, args).finally(() => bump(-1));
};
const origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (...args) {
bump(1);
this.addEventListener('loadend', () => bump(-1), { once: true });
return origSend.apply(this, args);
};
}`;
async function waitForNetworkIdle(driver, timeout = 20000, quietMs = 500) {
await driver.executeScript(TRACKER);
await driver.wait(() => driver.executeScript(
"return document.readyState === 'complete' && window.__net.pending === 0 " +
'&& Date.now() - window.__net.last > arguments[0];', quietMs), timeout, 'network never went idle');
}
await driver.get('https://app.example.com/dashboard');
await waitForNetworkIdle(driver);
const string Tracker = """
if (!window.__net) {
window.__net = { pending: 0, last: Date.now() };
const bump = (d) => { window.__net.pending += d; window.__net.last = Date.now(); };
const origFetch = window.fetch;
window.fetch = function (...args) {
bump(1);
return origFetch.apply(this, args).finally(() => bump(-1));
};
const origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (...args) {
bump(1);
this.addEventListener('loadend', () => bump(-1), { once: true });
return origSend.apply(this, args);
};
}
""";
public static void WaitForNetworkIdle(IWebDriver driver, TimeSpan timeout, long quietMs = 500)
{
var js = (IJavaScriptExecutor)driver;
js.ExecuteScript(Tracker);
new WebDriverWait(driver, timeout).Until(_ => (bool)js.ExecuteScript(
"return document.readyState === 'complete' && window.__net.pending === 0 " +
"&& Date.now() - window.__net.last > arguments[0];", quietMs));
}
driver.Navigate().GoToUrl("https://app.example.com/dashboard");
WaitForNetworkIdle(driver, TimeSpan.FromSeconds(20));

Why It Works

Almost every single-page app talks to its backend through fetch or XMLHttpRequest. Wrapping both gives an exact in-flight count, and the quiet window handles chains where one response triggers the next request a few milliseconds later. The guard (if (!window.__net)) makes the injection safe to call repeatedly, and the wait returns as soon as the page is genuinely quiet.

When to Use Something Else

SituationBetter option
A specific element or text signals completionWait for that. It is more meaningful than “network idle”.
A loading overlay existsWait for the spinner to disappear
You need to catch requests made during the initial page loadBiDi network events (beforeRequestSent / responseCompleted), subscribed before navigation. See BiDi Network Interception.
WebSockets, polling or analytics beacons keep firingIdle never happens; wait for an element instead.

Gotchas

  • Requests during page load are missed. The tracker is installed after get() returns, so requests already in flight are not counted. The readyState check and the quiet window cover most of these; for full coverage, install the tracker as a BiDi preload script (script.addPreloadScript) so it runs before the page’s own scripts.
  • Re-inject after navigation. A full page load wipes window.__net. Call the wait again after every get(), refresh or link that reloads the page. Client-side route changes in an SPA keep it.
  • Long polling keeps pending at 1 forever. Exclude those URLs inside the wrapper (check args[0]) if your app uses them.
  • Do not use this as a universal wait. Network idle says nothing about rendering. Follow it with an assertion on the element you actually care about.

Learn the theory