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

Pass the same test-scoped Playwright Page to the page objects that need it, keep each locator with the object responsible for that part of the UI, and compose a small component object when a genuinely shared control appears on multiple pages. A Playwright Locator is a reusable query, not a saved DOM element: it resolves against the current page when an action or assertion uses it.

This keeps ownership clear without forcing every page into a common base class. The examples below use TypeScript and Playwright Test.

What “sharing a locator” should mean

In a page-object model, each object provides a higher-level API for a meaningful page or part of an application. Playwright’s documented pattern is to pass a Page into a page-object constructor, store the page, and define its locators there. That places selectors near the behavior that uses them and avoids scattering selector definitions across tests. See the Playwright page object models documentation.

Sharing should generally mean reusing a locator definition or component behavior against the same relevant page—not sharing a browser element snapshot across tests. If a header is on several pages, for example, each page object can compose a Header object that uses its own page. Each test still receives its own page through Playwright Test’s fixture system.

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.

For a single repeated line in a simple test, an abstraction may make the test harder to read than the duplication it removes. Playwright’s best-practices guidance allows small duplication when it keeps simple tests clear. See Playwright best practices.

Build a shared component with composition

Use composition when the UI itself is shared and its controls or behavior belong together. Pass the containing Page or a locator for the component root, then define component locators once. The following example scopes the header to a root locator so it can also work when the header is nested inside a larger page region.

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

class Header {
  readonly accountButton: Locator;

  constructor(root: Page | Locator) {
    this.accountButton = root.getByRole('button', { name: 'Account' });
  }

  async openAccountMenu(): Promise<void> {
    await this.accountButton.click();
  }
}

class OrdersPage {
  readonly header: Header;
  readonly heading: Locator;

  constructor(readonly page: Page) {
    this.header = new Header(page);
    this.heading = page.getByRole('heading', { name: 'Orders' });
  }

  async expectLoaded(): Promise<void> {
    await expect(this.heading).toBeVisible();
  }
}

class ProfilePage {
  readonly header: Header;
  readonly heading: Locator;

  constructor(readonly page: Page) {
    this.header = new Header(page);
    this.heading = page.getByRole('heading', { name: 'Profile' });
  }
}

The classes share the Header definition, but each instance is built from the page passed to its owning page object. The page objects retain their own page-specific headings. The component pattern is an architectural recommendation based on Playwright’s page-object and locator APIs; Playwright does not require a particular component hierarchy.

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.

Scope a component to a repeated region

If the page has multiple similar controls, first identify a stable root for the particular component, then create the component from that root. For example:

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.
class SearchPanel {
  readonly searchButton: Locator;

  constructor(root: Locator) {
    this.searchButton = root.getByRole('button', { name: 'Search' });
  }
}

class CatalogPage {
  readonly search: SearchPanel;

  constructor(readonly page: Page) {
    const panel = page.getByRole('region', { name: 'Catalog search' });
    this.search = new SearchPanel(panel);
  }
}

Root scoping makes the component’s ownership explicit and helps distinguish it from a similarly named control elsewhere. Adjust the root role and accessible name to match the application.

Choose locators that survive ordinary UI changes

Prefer locators that describe what a user or assistive technology can identify. Playwright recommends role locators with accessible names where practical; labels and text can also identify intended controls. A test ID is a reasonable choice when the team deliberately treats it as a stable testing contract or a user-facing locator cannot distinguish the target. See Playwright locators and the best-practices guidance.

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.
page.getByRole('button', { name: 'Save changes' });
page.getByLabel('Email address');
page.getByTestId('account-menu');

CSS and XPath are available, but selectors coupled to long chains of DOM structure can break when markup is reorganized. Likewise, do not resolve ambiguity automatically with .first(), .last(), or .nth(). First make the locator meaningful and unique; positional selection can silently point at another element after the page changes.

Understand locator lifetime and reuse

A stored locator is not a handle to one particular element instance. Playwright evaluates it when an action or assertion runs; if the page rerenders between operations, the locator resolves against the current DOM again. That is why it is usually safe to keep a Locator as a page-object property rather than reacquiring it after every render. This behavior is documented in Playwright’s locator guide.

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

Re-resolution does not make an incorrect locator correct. If it matches multiple elements, is detached from the intended region, or no longer describes the intended control, refine the locator or its scope. Avoid caching raw element state as a substitute for a locator when the page can change.

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

Construct page objects from Playwright Test fixtures

The built-in page fixture gives a test an isolated page. A custom fixture can construct page objects from that page and inject them into tests as named parameters. Playwright’s fixture documentation shows the general custom-fixture pattern and isolation model: Playwright Test fixtures.

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

class LoginPage {
  constructor(readonly page: import('@playwright/test').Page) {}

  readonly email = this.page.getByLabel('Email address');
  readonly password = this.page.getByLabel('Password');
  readonly signInButton = this.page.getByRole('button', { name: 'Sign in' });

  async signIn(email: string, password: string): Promise<void> {
    await this.email.fill(email);
    await this.password.fill(password);
    await this.signInButton.click();
  }
}

type AppFixtures = {
  loginPage: LoginPage;
  ordersPage: OrdersPage;
};

export const test = base.extend<AppFixtures>({
  loginPage: async ({ page }, use) => {
    await use(new LoginPage(page));
  },
  ordersPage: async ({ page }, use) => {
    await use(new OrdersPage(page));
  },
});

export { expect };

Then a test requests the object it needs:

import { test, expect } from './fixtures';

test('opens the account menu from Orders', async ({ page, ordersPage }) => {
  await page.goto('/orders');
  await ordersPage.expectLoaded();
  await ordersPage.header.openAccountMenu();
  await expect(ordersPage.header.accountButton).toBeVisible();
});

Here the fixture creates the page objects using the same test-scoped page. Requesting both page objects does not create a second page. If a test genuinely needs independent tabs or contexts, model those explicitly rather than accidentally sharing a fixture object across tests. Keep page-object setup aligned with Playwright’s fixture lifecycle.

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

Composition, inheritance, or a little duplication?

Approach Good fit Watch for
Composed component object A real UI component appears on multiple pages and has its own controls or behavior. Do not extract components that are only superficially similar; keep the root scope and ownership clear.
Base page class A small set of behavior is genuinely common to all pages and inheritance makes that relationship easier to understand. Do not use a base class just to centralize every locator; the official Playwright material does not prescribe an inheritance hierarchy.
Small duplication The behavior is simple and repeating a line keeps each test or page class easier to follow. If the repeated UI behavior changes in several places, reassess whether it is a real shared component.

Make the decision by asking whether the UI is truly shared, whether the abstraction keeps locators scoped, whether changes to the shared UI should affect every consumer together, and whether the abstraction makes a straightforward test harder to follow. These are design criteria, not framework rules.

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

Troubleshoot common sharing problems

A component locator matches the wrong control

  • Cause: The locator is created from the whole page and the same role or name appears elsewhere.
  • Fix: Identify the component’s root with a meaningful role, accessible name, or test ID, then construct the component using that root locator.

A positional locator changes target after a UI update

  • Cause: .first(), .last(), or .nth() encodes order rather than intent.
  • Fix: Add a stable scope or use a role, label, text, or agreed test ID that identifies the intended element.

A locator appears stale after a rerender

  • Cause: The locator is assumed to be a saved DOM element, or the query no longer matches the current page.
  • Fix: Remember that locators resolve when used. Check that the page is in the expected state and that the locator still uniquely describes the control.

Page objects unexpectedly affect each other

  • Cause: Objects are reused outside the test-scoped fixture lifecycle or constructed with the wrong page.
  • Fix: Construct the objects from the test’s injected page in a fixture, and keep their lifetime aligned with that test.

A shared class becomes hard to maintain

  • Cause: The abstraction combines unrelated controls or forces pages with different UI into the same hierarchy.
  • Fix: Split genuinely independent components, or keep the simple duplication if that is clearer. The official guidance does not identify one universally best architecture.

Or skip the browser setup

If your goal is to capture a website rather than build an automated test, ScreenshotNeo offers a website screenshot API and MCP server. A single GET request can return a PNG, JPEG, WebP, or PDF:

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 API documentation for request options. Cookie banners and consent overlays, newsletter popups, and chat widgets can be removed before capture; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response reports the page verdict and billing status in headers. Its MCP server provides screenshot tools for AI agents and MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

Sign up free for ScreenshotNeo.

Frequently Asked Questions

Does Playwright require a base page class for shared locators?

No. Playwright documents page objects as a way to organize selectors and reusable code, but does not require inheritance or prescribe a component hierarchy.

Can two page objects use the same Playwright Page?

Yes. When both objects belong to the same test, construct them with that test’s injected page. Their locators will operate on that page.

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

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.