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

To move the main document to its exact top in Playwright, run await page.evaluate(() => window.scrollTo(0, 0));. For an inner scrollable panel, select that element and set its scrollTop to zero. Use scrollIntoViewIfNeeded() when you only need a particular element visible, and use mouse.wheel() when the test must reproduce real wheel input.

The direct solutions

Playwright executes page.evaluate() in the browser page context. That makes the browser’s window.scrollTo() the simplest deterministic way to reset the document viewport:

await page.evaluate(() => window.scrollTo(0, 0));

A nested menu, feed, modal, or panel has its own scroll position. Reset the specific element instead of the window:

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

The Playwright documentation’s scrolling guide covers automatic scrolling, locator evaluation, and wheel input at playwright.dev/docs/next/input. The page-evaluation API is described at playwright.dev/docs/api/class-page.

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.

Choose the operation that matches the requirement

Requirement Use What it guarantees
Reset the whole document page.evaluate(() => window.scrollTo(0, 0)) Requests document coordinates x = 0, y = 0.
Reset an inner scrolling region locator.evaluate(element => element.scrollTop = 0) Changes that element’s vertical position without moving the page viewport.
Expose a known target locator.scrollIntoViewIfNeeded() Scrolls only when the target is not completely visible; it does not promise a page coordinate of zero.
Reproduce user wheel input page.mouse.wheel(0, amount) Moves by a wheel delta; it is not an exact-position command.

Most Playwright actions already scroll their target into view before acting. Add explicit scrolling when the scroll position itself is part of the test, when you are preparing a capture, or when an application has a separately scrolling container. Otherwise, an extra scroll can make a test slower without adding coverage.

Scroll the whole page to the top

TypeScript or JavaScript

This is the minimal document-level operation:

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

test('returns the document to the top', async ({ page }) => {
  await page.goto('https://example.com');
  await page.evaluate(() => window.scrollTo(0, 0));

  const y = await page.evaluate(() => window.scrollY);
  expect(y).toBe(0);
});

The callback is evaluated after navigation in the page itself, so window refers to the page being tested rather than Node.js. Keep the scroll after the navigation or other action that moved the page. If a later operation triggers another navigation or application state change, perform the reset after that operation.

Reset both horizontal and vertical coordinates

window.scrollTo(0, 0) also requests a horizontal position of zero. This matters on wide tables or pages with horizontal overflow. If your test needs to record the resulting position, return it from the page context:

const position = await page.evaluate(() => {
  window.scrollTo(0, 0);
  return { x: window.scrollX, y: window.scrollY };
});
console.log(position);

Use the returned values for diagnostics rather than assuming that a call made before a layout change remains the final state.

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

Reset a nested scrollable element

A page can be at the top while an inner element remains halfway through a feed. Target the element that owns the scrollbar:

const feed = page.getByTestId('scrolling-container');
await feed.evaluate(element => {
  element.scrollTop = 0;
});

The locator is resolved before its callback runs, so this approach also benefits from Playwright’s normal locator waiting. Use a stable test ID, role, or other locator that identifies the actual scrolling element, not a child card inside it.

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.

When the panel is horizontally scrolled

For a two-dimensional panel, reset both properties in the same evaluation:

await feed.evaluate(element => {
  element.scrollTop = 0;
  element.scrollLeft = 0;
});

If the selected node is not the element with overflow and a scrollbar, changing its position will have no visible effect. Select the nearest scrolling ancestor instead.

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.

Frames and shadow-root content

Scrolling is scoped to the browsing context. For an element inside an iframe, first obtain the frame locator and then evaluate against the inner element:

const frame = page.frameLocator('iframe[ title="Results" ]');
await frame.getByTestId('scrolling-container').evaluate(element => {
  element.scrollTop = 0;
});

For shadow DOM, use a locator that resolves to the element inside the component. The key distinction remains the same: evaluate window for the document, or the element that owns the scroll position for a nested region.

Bring an element into view instead of forcing the page to zero

If the requirement is “show the heading” or “make the button visible,” do not reset the entire document. Playwright’s locator API provides:

await page
  .getByRole('heading', { name: 'Page title' })
  .scrollIntoViewIfNeeded();

scrollIntoViewIfNeeded() waits for actionability checks and scrolls only when the element is not completely visible. The locator reference documents this behavior at playwright.dev/docs/api/class-locator. It is appropriate when the final coordinate is not important, such as preparing a click or an assertion on a heading.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

This method can leave the target near an edge of the viewport and can move a nested container rather than the document. Use the explicit window.scrollTo(0, 0) or scrollTop = 0 forms when your assertion is about an exact top position.

Simulate a real mouse wheel

Wheel input is useful when the application listens for wheel events, lazy-loads content in response to user scrolling, or when interaction fidelity matters:

const panel = page.getByTestId('scrolling-container');
await panel.hover();
await page.mouse.wheel(0, -500);

Hovering the panel gives the pointer a scroll target before sending the wheel event. A negative vertical delta normally moves upward and a positive delta downward, but the amount is controlled by the browser and page behavior. Repeated wheel events can therefore stop short of the exact top. To guarantee zero, use direct position control after the interaction, or use direct control alone when no wheel event needs to be tested.

A complete, repeatable test pattern

The following test demonstrates navigation, an intentional downward move, a deterministic reset, and a check of the browser position:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { test, expect } from '@playwright/test';

test('resets the document after a long-page interaction', async ({ page }) => {
  await page.goto('https://example.com/long-page');

  await page.mouse.wheel(0, 1200);
  await page.evaluate(() => window.scrollTo(0, 0));

  const { x, y } = await page.evaluate(() => ({
    x: window.scrollX,
    y: window.scrollY
  }));
  expect(x).toBe(0);
  expect(y).toBe(0);
});

For a component test, keep the document untouched and verify the component’s own property:

test('resets the results panel', async ({ page }) => {
  await page.goto('https://example.com/results');
  const panel = page.getByTestId('scrolling-container');

  await panel.evaluate(element => {
    element.scrollTop = 0;
  });

  await expect.poll(async () => {
    return panel.evaluate(element => element.scrollTop);
  }).toBe(0);
});

The polling assertion is useful when the page has code that reacts to a scroll event and might immediately adjust the position. If your Playwright version or assertion setup does not include polling, read the value with panel.evaluate() and assert it in your test language.

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

Java and other language bindings

The API shape differs by binding, but the operation is the same. In Java, a locator evaluation callback can set scrollTop:

Locator panel = page.getByTestId("scrolling-container");
panel.evaluate("element -> element.scrollTop = 0");

Java wheel input uses the mouse API as well:

panel.hover();
page.mouse().wheel(0, -500);

Playwright’s Java scrolling examples are available at playwright.dev/java/docs/input. Translate the callback syntax and locator construction to the binding you use; do not mix a JavaScript callback with a Java API call.

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

Timing, layout, and reliability considerations

Run the reset after the state change

Infinite lists, route transitions, and client-side renders can move the viewport after your first evaluation. Wait for the relevant navigation, content, or locator state, then reset. If the application intentionally restores a saved scroll position, your test should reset after that restoration or disable the behavior in the test fixture.

Do not confuse sticky headers with a nonzero scroll

A fixed or sticky header can remain visible even when window.scrollY is zero. That is a layout effect, not evidence that the page failed to reset. Assert the numeric position when the coordinate matters, and assert element visibility when the visual requirement is what matters.

Lazy loading and infinite scrolling

Returning to the top does not remove content that was already loaded. If the test needs a fresh list, reload or reset the application’s data state separately. Conversely, use wheel input when the behavior under test is the loading trigger itself; use direct position control when you only need a known starting coordinate.

Animations and smooth scrolling

A page can apply smooth-scroll behavior or run scroll handlers. Read back window.scrollY or the element’s scrollTop after the operation if the next assertion depends on the final position. A direct assignment expresses the desired endpoint; the application can still react afterward.

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

Troubleshooting

Symptom Likely cause Fix
The page stays in the same place. You changed a nested element, but the document is the scroller, or a later render restored the position. Use page.evaluate(() => window.scrollTo(0, 0)) for the document and run it after the render or navigation.
The panel does not move. The locator identifies a child rather than the element with the scrollbar. Inspect the DOM and target the scrolling container; set its scrollTop.
Wheel scrolling affects the wrong area. The pointer is not over the intended container. Call await panel.hover() before page.mouse.wheel().
The target is visible but not at the top. scrollIntoViewIfNeeded() guarantees visibility, not a zero coordinate. Use the exact document or element reset when placement matters.
An iframe’s content does not respond. The evaluation ran in the parent page context. Use a frame locator and evaluate the element inside that frame.
The value briefly reaches zero and changes again. Application scroll restoration, a scroll handler, or an infinite-list update runs afterward. Wait for the state that causes the update, reset at the final point, and poll the resulting position.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and cost of each approach

  • Direct evaluation is one browser-context call and is normally the least work for an exact reset.
  • Locator evaluation adds locator resolution but correctly scopes the operation to a component.
  • scrollIntoViewIfNeeded() performs actionability checks and may move one of several scrollable ancestors.
  • Wheel simulation can require multiple events and is best reserved for tests of scroll-driven behavior.

All four approaches run inside your Playwright browser session. They do not change the application’s server data, clear loaded content, or create a new page; they only change scroll state or visibility.

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.

Or skip the browser setup

If your real goal is a website image rather than testing scroll interaction, ScreenshotNeo can return a screenshot from one HTTP request. It is a website screenshot API and MCP server; see the ScreenshotNeo documentation for parameters and response details.

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

Python:

import requests
r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
const buffer = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', buffer));

ScreenshotNeo accepts PNG, JPEG, WebP, or PDF output and can also capture full pages, selected elements, and customized viewports. Before capture it can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed as clean shots, and responses identify the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

Plan Allowance Price
Free 1,000 shots per month $0, no card
Starter 3,000 shots $5
Growth 15,000 shots $15
Pro 60,000 shots $39
Scale 250,000 shots $99
Business 1,000,000 shots $249

Every feature is included on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account to get 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots.

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

FAQ

How can I identify the element that actually scrolls?

In browser developer tools, scroll the suspected panel and watch which node’s position changes. The correct locator is the element whose own vertical scrollbar moves, not necessarily the visible list item inside it.

Does resetting scroll clear a browser’s saved position?

No. It changes the current page or element position for that session. A reload, route change, or application-level scroll-restoration feature can establish a different position later.

Can I use this technique for a screenshot baseline?

Yes. Reset the relevant document or container before calling your screenshot assertion so the capture starts from a known state. If the image is the only output you need, the ScreenshotNeo request above avoids maintaining a Playwright browser session.

Frequently Asked Questions

How can I identify the element that actually scrolls?

In browser developer tools, scroll the suspected panel and watch which node’s position changes. The correct locator is the element whose own vertical scrollbar moves, not necessarily the visible list item inside it.

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.

Does resetting scroll clear a browser’s saved position?

No. It changes the current page or element position for that session. A reload, route change, or application-level scroll-restoration feature can establish a different position later.

Can I use this technique for a screenshot baseline?

Yes. Reset the relevant document or container before calling your screenshot assertion so the capture starts from a known state. If the image is the only output you need, the ScreenshotNeo request above avoids maintaining a Playwright browser session.

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.