Race condition in Playwright .NET during click-to-navigate with WaitForURLAsync

99 views Asked by At

I'm using Playwright with the .NET bindings.

There used to be a problem where causing a navigation via a click could lead to a race condition, i.e.:

await page.ClickAsync(".foo");         // indirectly causes a navigation
await page.WaitForNavigationAsync();   // race condition; times out

That was a problem inherited from Puppeteer (of which Playwright is a fork) and the same workaround was recommended (even though it should work in .NET, this pattern was needed due to the cs-js interop):

var task = page.WaitForNavigationAsync();
await page.ClickAsync(".foo");
await task;

Since then Playwright introduced WaitForURLAsync feature which was supposed to eliminate that problem:

await page.ClickAsync(".foo");
await page.WaitForURLAsync();

I assume that works for others. But I'm using the .NET bindings, and I see this issue when scraping a SPA; when I use the old workaround, the problems disappear:

var task = page.WaitForURLAsync();
await page.ClickAsync(".foo");
await task;

I can't post a repro for a specific site as it's confidential. But I wonder whether this new .NET method was implemented to have the same behaviour as the Node version? Has anyone else encountered this problem, and what remedy did you take?

1

There are 1 answers

0
Gaurav Khurana On

You can user wait for an event in below fashion as explained here and it helps

var waitForRequestTask = page.WaitForRequestAsync("**/*logo*.png");
await page.ClickAsync(".foo");
var request = await waitForRequestTask;

Alternatively expect can be used, then it will wait for it before moving forward

Expect(Page.locator("Element on target page")).ToBeVisibleAsync()