How can I wait for all xhr request to be done

Viewed 2112

I click on button that trigger http request And I want to be able to close the page after the request done.

Example: Await page.click(some button that trigger http request)

I have tried :Await page.waitForLoadState() With “load” and “networkidle” and its didnt work. For load the page closed without the request finish and for networkidle waiting until timeout.

I want to be able to wait for all the xhr request in the background to be finished

1 Answers

Its a web limitation, that you can't wait for all the requests to be done. What are all requests? What if there are requests every 50ms?

In your case you probably want to wait for a specific request:

// Note that Promise.all prevents a race condition
// between clicking and waiting for the response.
const [response] = await Promise.all([
  // Waits for the next response with the specified url
  page.waitForResponse('https://example.com/resource'),
  // Triggers the response
  page.click('button.triggers-response'),
]);

// Alternative way with a predicate.
const [response] = await Promise.all([
  // Waits for the next response matching some conditions
  page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200),
  // Triggers the response
  page.click('button.triggers-response'),
]);

See here: https://playwright.dev/docs/api/class-page#page-wait-for-response

Related