How to wait for HTML Element replacement in Playwright

180 views Asked by At

I have a webpage that does AJAX requests and replaces parts of the page with the response HTML.

I want to detect when an HTML element on the DOM gets replaced with new content, in order to verify the data the new content contains.

I was expecting that this would work, but apparently it doesn't:

    // Get element.
    var elements = page.Locator(".element-class");
    var count = await elements.CountAsync();
    if (count != 1) throw new Exception("Unexpected element count!");
    var element = elements.First;

    // Wait for it to be detached.
    await element.WaitForAsync(new LocatorWaitForOptions { State = WaitForSelectorState.Detached });

All I get is a timeout, after a long wait.

I use the latest nuget package for Microsoft.Playwright (v 1.39.0).

The page also uses a loader while doing the AJAX calls, but I can't use that either since it gets "hidden" by being pushed outside the screen and I found no way to wait for inline CSS property changes. Perhaps I could roll out my own version for this check, by doing CSS checks in a loop, but I was hoping there is a better/simpler way to solve the problem above.

Update:

It seems to work when using it on an overlay element that blocks clicks while doing the AJAX, so something is different for the case above:

    var elements = page.Locator(".topoverlay");
    await elements.WaitForAsync();
    var count = await elements.CountAsync();
    if (count != 1) throw new Exception("Unexpected element count!");
    var element = elements.First;
    await element.WaitForAsync(new LocatorWaitForOptions { State = WaitForSelectorState.Detached, Timeout = Timeout });

Perhaps I need to target the exact element that gets detached (by the replacement) and not a child of it?

Or maybe replacing elements on the DOM is not captured by Playwright, since there is little to no difference between old and new HTML?

0

There are 0 answers