How do I scroll to bottom of the page with Javascript but with some delay using selenium?

Palak Shah

Well-known member
Joined
Apr 29, 2020
Messages
97
Programming Experience
1-3
Good day, everyone!

I have a web page with lazy loading enabled, and I'd like to scroll to the bottom of the page, but with a wait, so that the new components in the page may be seen.

At the present, I'm trying JavaScript, but it just scrolls to the bottom of the page, which doesn't reveal any new elements, and my tests fail as a result.

Could someone please assist me?

Below Is the code for ScrollToBottom

C#:
public static void ScrollToBottom(this IWebDriver Driver)
    {
        
        Driver.ExecuteJavaScript("window.scrollTo({ top:  document.body.scrollHeight, behavior: 'smooth' })");
    }

And Entire code for ScrollUntilNoLazyLoad

C#:
public static void ScrollUntilNoLazyLoad(this IWebDriver Driver, string locator = null)
    {
        ThreadHelper.VoidWait(() =>
        {
            var before = Driver.PageSource;
            Driver.ScrollToBottom();
            Thread.Sleep(2000);

            var after = Driver.PageSource;
            if (!before.Equals(after))
                Driver.ExecuteJavaScript("window.scrollBy(0, -250)");
            Thread.Sleep(2000);

            var after2 = Driver.PageSource;
            if (locator.IsNullOrEmpty())
            {
                if (!before.Equals(after2))
                    throw new ArgumentException("due to lazy load new items have been added, scrolling will continue.");
            }
            else
            {
                if (Driver.TryFind(locator, IWebElementState.Displayed, 500).IsNull())
                    throw new ArgumentException("Element is not yet displayed!");
            }
        }, false);
    }
 
Sorry, I'm not familiar enough with Selenium and how it does looping and yielding control back to the browser.
 
Back
Top Bottom