October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk8 min

How to Use the Page Object Model with Selenium and JavaScript

Use JavaScript page objects to centralize Selenium selectors and actions while keeping test assertions clear and maintaining browser cleanup.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a Page Object to keep a page’s selectors and user-facing browser operations in one JavaScript class, then let tests call those operations and own the assertions. This structure makes UI changes easier to maintain because page-specific knowledge is centralized instead of repeated across tests.

What the Page Object Model means in Selenium

A Page Object represents a web page—or a meaningful part of one—as an object that test code can use. Its methods express actions and observations such as signing in, searching, or reading a heading. The test describes the scenario and checks whether the outcome is correct.

Selenium’s official guidance presents Page Objects as a way to reduce duplicated code and keep page-specific changes in one place. Its canonical examples are primarily in Java, so the JavaScript implementation below applies those design principles using Selenium’s JavaScript binding rather than copying Java syntax. Selenium: Page object models

Set up Selenium WebDriver for JavaScript

The Selenium JavaScript binding is the selenium-webdriver npm package. The official API reference accessed on October 3, 2026 specifies Node.js 22 or newer. It documents installation with npm and says Selenium Manager handles browser-driver installation automatically. Check the current API reference when choosing a runtime, since runtime support dates can change. Selenium JavaScript API reference

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Install Node.js 22 or newer and create a project directory.

  2. Initialize the project and install Selenium:

    npm init -y
    npm install selenium-webdriver

  3. Save the following example as login-test.js. It uses Node’s built-in strict assertion module, so no separate test framework is required to run this single example.

  4. Run it with node login-test.js. Replace the example URL and expected heading with values from an application and test environment you control.

Build page objects around behavior

This illustrative JavaScript adaptation has not been claimed as executed or verified. Update its selectors, URL, and expected text for your application. The page object keeps locators private to the page’s implementation and exposes meaningful actions and observations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const { Builder, By } = require('selenium-webdriver')
const assert = require('node:assert/strict')

class LoginPage {
  constructor(driver) {
    this.driver = driver
    this.username = By.name('username')
    this.password = By.name('password')
    this.submit = By.css('button[type="submit"]')
  }

  async open() {
    await this.driver.get('https://example.test/login')
  }

  async signIn(username, password) {
    await this.driver.findElement(this.username).sendKeys(username)
    await this.driver.findElement(this.password).sendKeys(password)
    await this.driver.findElement(this.submit).click()
    return new HomePage(this.driver)
  }
}

class HomePage {
  constructor(driver) {
    this.driver = driver
    this.heading = By.css('h1')
  }

  async headingText() {
    return this.driver.findElement(this.heading).getText()
  }
}

async function main() {
  const driver = await new Builder().forBrowser('chrome').build()

  try {
    const login = new LoginPage(driver)
    await login.open()
    const home = await login.signIn('reader', 'example-password')
    assert.equal(await home.headingText(), 'Welcome')
  } finally {
    await driver.quit()
  }
}

main().catch((error) => {
  console.error(error)
  process.exitCode = 1
})

The test controls the WebDriver session, opens the login page, performs the action through the page object, and checks the result. Returning a HomePage from signIn models the successful transition. If login can instead remain on the form and show an error, make that outcome explicit in the page-object API—for example, with a distinct method or a result object—and have the test inspect the resulting state.

Keep responsibilities clear

Choose page objects, components, and execution location

Choice Best fit Trade-off
Page object A page-level flow or behavior used by tests, such as signing in or reading a page heading. One object may become unwieldy if it absorbs unrelated regions or behaviors; extract components where that improves reuse and readability.
Component object A repeated or meaningful region, such as a product card or site navigation, especially when lookups should be scoped to that region. Introduces another abstraction; use it when the component has useful behavior or reuse, not merely to wrap every element.
Local WebDriver Running a browser session on the machine executing the test, using a Builder for the desired browser. The local machine supplies the browser environment and executes the session.
Remote WebDriver Running the browser session through a Selenium Grid or standalone remote server. Requires an available remote Selenium endpoint; the browser session runs at that server rather than as a local browser session.

The Selenium JavaScript API documents both local Builder setup and remote configuration using usingServer; it also documents the SELENIUM_REMOTE_URL environment variable for a remote URL. Selenium JavaScript API reference

Build a Page Object Model incrementally

  1. Choose one real user flow and list only the page operations its test needs.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  2. Create a class for each page with meaningful behavior. Put that page’s selectors and interaction methods in the class.

  3. Pass the WebDriver into each object so the test setup retains control of the browser session.

  4. When an operation navigates, return an object for the page reached. If an operation can lead to distinct outcomes, make those paths clear and let the test inspect the relevant result.

  5. Keep assertions and scenario-specific expected values in the test. Add only a narrow readiness check to construction if it helps prevent using an object for the wrong page.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  6. Extract a repeated region into a component object when reuse or scoped lookups make the test design clearer.

  7. Always quit the driver in a finally block so cleanup still runs when navigation, an interaction, or an assertion fails.

Local and remote browser setup

Run locally

The example’s new Builder().forBrowser('chrome').build() creates a local Chrome session. Selenium’s JavaScript API documentation says Selenium Manager automatically handles browser-driver installation. The example still requires a suitable browser environment on the machine running it.

Connect to a remote Selenium server

For a Grid or standalone server, configure the Builder with the server URL before building the driver:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const { Builder } = require('selenium-webdriver')

const driver = await new Builder()
  .usingServer(process.env.SELENIUM_REMOTE_URL)
  .forBrowser('chrome')
  .build()

Set SELENIUM_REMOTE_URL to the endpoint provided by your Selenium server. Keep the same page-object and test structure: the test still controls the driver, while the configured endpoint determines where the browser session runs.

Troubleshoot common failures

  • Node.js version is rejected or the package cannot run. Confirm that the runtime meets the API reference’s stated Node.js 22 minimum. The reference accessed October 3, 2026 lists support ending April 30, 2027 for Node.js 22, April 30, 2028 for Node.js 24, and April 30, 2029 for Node.js 26. Confirm current dates in the reference before selecting a runtime.

  • A locator cannot find an element. Check that the selector matches the current page, that navigation reached the expected page, and that the element is present before the lookup. Keep the selector in the page object so the fix stays centralized.

  • The test fails after a successful click. Confirm whether the action actually navigates or produces another state, such as an inline error. Make the page-object method’s return value reflect the intended path, then have the test inspect the appropriate page or state.

    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.
  • A browser session is not created locally. Verify the browser is available in the execution environment and that the selected browser name is supported there. Consult Selenium’s current setup documentation if the environment cannot create a session.

  • A remote session cannot connect. Confirm that the Grid or standalone server is running and reachable, and that SELENIUM_REMOTE_URL points to its configured endpoint. The remote Builder option does not itself provide or start a server.

  • The driver remains open after an error. Place all test actions inside a try block and call await driver.quit() from finally, as in the complete example.

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

Performance, reliability, and maintenance

Page Objects are an organization pattern; they do not by themselves make browser navigation or interactions faster. Their practical value is reducing duplicated selectors and interactions, which can make UI maintenance more localized. Avoid layering abstractions that merely rename individual WebDriver calls: model behavior that makes a test easier to read or reuse.

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

Reliability still depends on the browser session, application state, and selectors used by the tests. A page object should describe how to operate on its page, while the test remains responsible for deciding whether the observed result passes the scenario. Use the documented setup appropriate to your environment, and ensure session cleanup runs even when the test fails.

Or skip the browser setup

If you need a screenshot rather than an interactive Selenium test, ScreenshotNeo is a website screenshot API and MCP server. One GET request can return a PNG, JPEG, WebP, or PDF. Its API can accept consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents.

Install the HTTP client with npm install only if using a package; this Node.js example uses built-in fetch and the same API key pattern as the service’s examples. Replace the target URL as needed:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' }); const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation for request options and response details. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo and get 1,000 free screenshots a month with no card.

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.

Frequently Asked Questions

Can a Page Object represent a component instead of a whole page?

Yes. A reusable region such as a product card or navigation area can have its own object, with lookups scoped beneath its root WebElement.

Should page objects contain assertions?

Keep scenario assertions in the test. A page object may make a narrow check that the expected page or a critical element loaded when the object is created.

Does Page Object Model speed up Selenium tests?

Not by itself. Its primary benefit is organizing UI knowledge so selectors and operations are easier to maintain.

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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.