Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a locator and call scrollIntoViewIfNeeded() when you need explicit scrolling:

await page.getByText('Footer text').scrollIntoViewIfNeeded();

In normal tests, you often do not need this line. Playwright automatically scrolls most targets into view before actions such as click(). Add an explicit scroll when you are loading an infinite list, positioning a page for a screenshot, working with a nested scrolling region, or verifying a no-scroll condition.

Choose the scrolling method that matches the problem

Method Best for How it behaves
locator.scrollIntoViewIfNeeded() Making a semantic target visible; infinite-list sentinels; screenshot setup Waits for actionability and scrolls only when the element is not completely visible
page.mouse.wheel() Simulating user wheel input, especially in a nested container Moves by a specified horizontal and vertical delta
locator.evaluate() Direct control of a known scrollable element Changes scrollTop or scrollLeft inside the page

Prefer semantic locators such as getByRole, getByText and getByTestId. They make the reason for the scroll clear and are less fragile than long CSS or XPath expressions.

Scroll a locator into view

JavaScript and TypeScript

import { test, expect } from '@playwright/test';

test('shows the pricing heading', async ({ page }) => {
  await page.goto('https://example.com');
  const target = page.getByRole('heading', { name: 'Pricing' });
  await target.scrollIntoViewIfNeeded();
  await expect(target).toBeVisible();
});

scrollIntoViewIfNeeded() is the preferred locator API. Playwright waits for its normal actionability checks, then uses an IntersectionObserver visibility ratio to determine whether scrolling is necessary. The Locator API lists this method as available since v1.14.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Python

from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto("https://example.com")
        target = page.get_by_role("heading", name="Pricing")
        await target.scroll_into_view_if_needed()
        await browser.close()

The synchronous Python binding uses the same method name without await:

target.scroll_into_view_if_needed()

Java

Locator target = page.getByRole(AriaRole.HEADING,
    new Page.GetByRoleOptions().setName("Pricing"));
target.scrollIntoViewIfNeeded();

.NET

var target = Page.GetByRole(AriaRole.Heading,
    new() { Name = "Pricing" });
await target.ScrollIntoViewIfNeededAsync();

Use the locator immediately before the assertion or action

Modern pages can reflow while images, ads or client-side components load. A locator is resolved at action time, so this pattern is safer than extracting a stale element handle early:

const save = page.getByRole('button', { name: 'Save' });
await save.scrollIntoViewIfNeeded();
await expect(save).toBeEnabled();
await save.click();

If the component is replaced during scrolling and an action reports that the element was detached, reacquire the locator after the update and retry the operation.

Does Playwright scroll automatically before clicking?

Yes. Playwright documents that “Most of the time, Playwright will automatically scroll for you before doing any actions.” This includes the normal work needed for:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.getByRole('button', { name: 'Submit' }).click();

Do not add an explicit scroll merely because a target is below the fold. Keep one when the scroll itself is part of the behavior under test, when you need deterministic screenshot composition, or when you must trigger lazy loading or infinite pagination.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Disable automatic scrolling deliberately

Actions that expose a scroll option can use scroll: 'none' to disable automatic scrolling:

await page.getByRole('button', { name: 'Submit' }).click({ scroll: 'none' });

This makes the action fail if the element is not already in the viewport. It is useful for testing a no-scroll requirement, not as a general performance optimization.

Scroll a nested container with the mouse wheel

When the page has an independently scrollable panel, identify that panel first. Hovering it gives wheel input a clear target:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const panel = page.getByTestId('scrolling-container');
await panel.hover();
await page.mouse.wheel(0, 10);

The first argument is horizontal movement and the second is vertical movement. Wheel input models what a user does, so it is useful for testing handlers, virtualized lists and interfaces where scrolling the document would be the wrong behavior. The exact amount of movement depends on the browser and page; assert on a visible result rather than assuming a particular pixel displacement.

Scroll until a target appears

const panel = page.getByTestId('scrolling-container');
const row = panel.getByRole('row', { name: 'Order 1042' });
for (let i = 0; i < 20; i++) {
  if (await row.isVisible()) break;
  await panel.hover();
  await page.mouse.wheel(0, 500);
}
await expect(row).toBeVisible();

For a production test, replace the fixed loop with an application-specific end condition and a timeout so a missing row does not create an unbounded test.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Set a container’s scroll position directly

For deterministic movement in a known scroll owner, run code in that element:

const panel = page.getByTestId('scrolling-container');
await panel.evaluate((element) => {
  element.scrollTop += 100;
});

You can assign an absolute position instead:

await panel.evaluate((element) => {
  element.scrollTop = element.scrollHeight - element.clientHeight;
});

This is useful when wheel events are intercepted or when a test needs an exact position. It does not prove that a real user can reach the same position with a wheel or keyboard, so use wheel input for interaction tests.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Find the actual scroll owner

  • The document viewport is usually the owner for a normal page.
  • A fixed-height element with overflow: auto or overflow: scroll owns its own scroll.
  • Modal dialogs, sidebars and virtualized grids commonly contain nested owners.
  • If scrolling appears to do nothing, inspect which ancestor’s scrollHeight exceeds its clientHeight.

Infinite lists and lazy-loaded content

To trigger pagination, scroll a bottom sentinel or footer into view. Playwright’s guidance describes this as the reliable way to make an element at the bottom visible:

const footer = page.getByText('End of results');
await footer.scrollIntoViewIfNeeded();
await expect(page.getByText('Loading more…')).toBeHidden();

For an infinite list with no permanent footer, use a sentinel selected by test ID:

for (let pageNumber = 0; pageNumber < 10; pageNumber++) {
  await page.getByTestId('list-bottom-sentinel').scrollIntoViewIfNeeded();
  const next = page.getByRole('button', { name: 'Load more' });
  if (await next.isVisible()) await next.click();
  if (await page.getByText('No more results').isVisible()) break;
}

Wait for the application’s loading indicator or a newly rendered item after each scroll. Scrolling alone does not guarantee that network requests or rendering have completed.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Prepare a page for a screenshot

Explicit scrolling can place a heading, chart or footer in a predictable composition before capture. Sticky headers may still cover the target, and a visible element can be partially obscured even when its locator reports visibility. Check the screenshot or use a layout assertion that accounts for the fixed header.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const chart = page.getByTestId('revenue-chart');
await chart.scrollIntoViewIfNeeded();
await expect(chart).toBeVisible();
await page.screenshot({ path: 'chart.webp', fullPage: false });

For a full-page capture, use fullPage: true; scrolling to one element first may still be useful when its lazy-loaded content appears only after it enters the viewport.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failures and fixes

“Element is not receiving pointer events”

A cookie banner, modal, chat widget or sticky layer may cover the target. Dismiss the overlay through its accessible control, wait for it to disappear, then scroll again. Do not solve a real obstruction with force: true unless the test specifically intends to bypass hit testing.

The target remains invisible

Verify the locator matches the intended element and that it is attached. For an iframe, enter the correct frame first with frameLocator(). For a hidden tab or accordion, open the parent control before scrolling.

Nested scrolling moves the page instead

Hover the container before mouse.wheel(), or use evaluate() on the container itself. Confirm that the container has scrollable overflow and that its content is taller than its client area.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The element detaches while scrolling

Virtualized lists may recycle DOM nodes. Use a stable locator, wait for the list update to settle, reacquire the locator, and then assert or act. Avoid retaining an ElementHandle across a re-render.

Click fails with scroll: 'none'

That failure is expected when the target is outside the viewport. Remove the option for normal behavior, or explicitly scroll first if the test is checking the post-scroll action.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Infinite loading never finishes

Wait for a specific network response or loading-state transition, check for a “no more results” condition, and cap the number of iterations. A sentinel can be visible while the request is still pending.

Performance, determinism and portability

  • Use locator scrolling for intent. It is concise and waits for Playwright’s actionability checks.
  • Use wheel input for realism. It exercises user-like scrolling but can vary with event handling and browser behavior.
  • Use evaluate for exact positions. It is deterministic, but it bypasses user input and should not replace interaction coverage.
  • Prefer semantic selectors. Roles, accessible names and test IDs survive layout changes better than coordinate-based scrolling.
  • Scroll close to the assertion. This reduces failures caused by reflow between setup and verification.
  • Keep timeouts bounded. Infinite-list loops and network waits need explicit limits.

The core concept is portable across official bindings: JavaScript uses scrollIntoViewIfNeeded(), Python uses scroll_into_view_if_needed(), Java uses scrollIntoViewIfNeeded(), and .NET uses ScrollIntoViewIfNeededAsync().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

If your goal is a clean page image rather than testing scrolling behavior, ScreenshotNeo provides a one-request screenshot API. Its capture options include full-page shots with lazy images loaded, element selection by CSS selector, device and viewport settings, dark mode, retina scale, custom CSS and JavaScript, click and wait actions, blocked ads or resource types, cookies and headers, caching, PDFs and bulk capture.

For a direct capture:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for every parameter. Cookie and consent banners, newsletter popups and chat widgets are accepted or removed before the shot; bot checks, blank pages, failed loads and timeouts are not billed, and response headers identify the page verdict and billing status. An MCP server supplies take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently asked questions

When was scrollIntoViewIfNeeded added?

The Locator API records it as available since Playwright v1.14.

Can I scroll horizontally?

Yes. Use a wheel delta such as page.mouse.wheel(300, 0), or set a container’s scrollLeft with evaluate().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does scrolling wait for network requests?

No. Scrolling changes visibility; wait separately for the loading indicator, response or newly rendered content your application uses.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.