Doctor Who
Doctor Who

Reputation: 1659

Playwright: How can I scroll to element to load fire lazy loading?

I have a page with hundreds of graphs that all display null values until you scroll them into view.

I want to assert the values for a specific graph that is halfway down the page, if I use scrollIntoViewIfNeeded() and read the text I still get the null value, if I look in playwright UI I can see it's not scrolling down the page so I'm assuming because playwright can find the element it's not bothering to do to scrollIntoViewIfNeeded().

Is there a way I can force it to scroll to the locators so the null values will be replaced with actual ones?

Upvotes: 2

Views: 2057

Answers (1)

emery
emery

Reputation: 9703

You can use page.evaluate() to execute JavaScript against the page to scroll to your lazy loading element:

const element = document.querySelector("YOUR_CSS_SELECTOR");
if (element) { element.scrollIntoView(); }

https://playwright.dev/docs/evaluating

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

Java example:

private void scrollIntoViewJs(String elementLocator) {
    String evalString = "const element = document.querySelector(\"" + elementLocator + "\");" +
            "if (element) {" +
                "element.scrollIntoView();" +
            "}";
    page.evaluate(evalString);
}

Upvotes: 1

Related Questions