Tal Turjeman
Tal Turjeman

Reputation: 61

How can I wait for all xhr request to be done

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

Upvotes: 6

Views: 13852

Answers (2)

Bruno Peres
Bruno Peres

Reputation: 3256

You can use waitForLoadState, with networkidle it waits until there are no network connections for at least 500 ms.

await popup.waitForLoadState('networkidle');

Do note that this is discouraged by the documentation though.

Upvotes: 8

Max Schmitt
Max Schmitt

Reputation: 3222

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

Upvotes: 9

Related Questions