Playwright JavaScript Examples: Step-by-Step Guide (2026)

1. Introduction to Playwright JavaScript Examples

Playwright is a modern open-source automation framework used to automate web applications across Chromium, Firefox, and WebKit browsers. It supports JavaScript, TypeScript, Python, Java, and .NET.

For QA Automation Engineers and SDETs, learning through practical Playwright JavaScript examples is one of the easiest ways to understand browser automation.

Unlike traditional Selenium scripts, Playwright provides built-in auto-waiting, powerful locators, browser contexts, network interception, and API testing capabilities.

In this tutorial, we will explore Playwright Code Examples from beginner to intermediate level. You will learn how to launch browsers, interact with web elements, automate login pages, validate API responses, and build reusable automation frameworks.

By the end, you will understand how to use Playwright JavaScript examples in real-world automation projects, regression testing, and SDET interviews.

What are Playwright JavaScript examples?

Playwright JavaScript examples are practical code snippets and automation scripts written using JavaScript and the Playwright library to interact with web applications.

Common use cases include:

2. Prerequisites and Project Setup

Before implementing Playwright JavaScript examples, install the following:

  • Node.js (LTS version).
  • npm package manager.
  • Visual Studio Code or another code editor.
  • Basic JavaScript knowledge.
  • Basic understanding of HTML and CSS.

Step 1: Create a project

Open the terminal and execute:

mkdir playwright-js-examples

cd playwright-js-examples

npm init -y

Step 2: Install Playwright Test

npm install -D @playwright/test

npx playwright install

The Playwright Test package includes the test runner, browser automation capabilities, assertions, fixtures, and reporting support.

Step 3: Create a test file

Create a folder named tests and add:

playwright-js-examples/

│

├── tests/

│   └── example.spec.js

├── playwright.config.js

└── package.json

For browser automation tests, use the Playwright Test runner. For one-time scripts or standalone automation tasks, you can use the standalone playwright library.

For example, install the standalone library when needed:

npm install playwright

3. Basic Playwright JavaScript Examples

Let’s start with browser launch, navigation, and page title validation.

Example 1: Launch a browser

Create browser.js:

const { chromium } = require(‘playwright’);

(async () => {

    const browser = await chromium.launch({

        headless: false

    });

    const page = await browser.newPage();

    await page.goto(‘https://www.google.com’);

    console.log(‘Browser launched successfully’);

    await browser.close();

})();

Explanation:

  • chromium.launch() launches the Chrome-based browser engine.
  • headless: false displays the browser window.
  • browser.newPage() creates a new page.
  • page.goto() navigates to the given URL.
  • browser.close() closes the browser.

Run the script:

node browser.js

Expected result: Chromium opens Google and then closes.

Example 2: Get page title and URL

const { chromium } = require(‘playwright’);

(async () => {

    const browser = await chromium.launch();

    const page = await browser.newPage();

    await page.goto(‘https://playwright.dev/’);

    const title = await page.title();

    const url = page.url();

    console.log(‘Page Title:’, title);

    console.log(‘Page URL:’, url);

    await browser.close();

})();

Expected result: The terminal displays the webpage title and current URL.

4. Playwright Locator Examples

Locators help Playwright identify and interact with web elements. Choosing reliable locators is important for stable test automation.

Example 3: Locate elements using different strategies

const { test, expect } = require(‘@playwright/test’);

test(‘Different locator examples‘, async ({ page }) => {

    await page.goto(‘https://www.saucedemo.com/’);

    // Locate using role

    const loginButton = page.getByRole(‘button’, {

        name: ‘Login’

    });

    // Locate using text

    const heading = page.getByText(‘Swag Labs’);

    // Locate using placeholder

    const username = page.getByPlaceholder(‘Username’);

    // Locate using label

    const password = page.getByLabel(‘Password’);

    // Locate using CSS selector

    const loginForm = page.locator(‘#login_button_container’);

    await expect(heading).toBeVisible();

    await expect(username).toBeVisible();

    await expect(password).toBeVisible();

    await expect(loginButton).toBeVisible();

    await expect(loginForm).toBeVisible();

});

Explanation:

LocatorPurpose
getByRole()Finds elements by accessible role and name
getByText()Finds elements using visible text
getByPlaceholder()Finds input fields by placeholder
getByLabel()Finds form controls by associated label
locator()Supports CSS and other selector strategies

Prefer role, label, and placeholder locators when possible. Use CSS selectors when user-facing attributes are unavailable or when a specific DOM relationship is required.

For more examples, link this section to your Playwright JavaScript Locators article.

5. JavaScript Automation Examples for Web Elements

Now let’s explore practical interactions used in everyday automation projects.

Example 4: Click buttons and fill forms

const { test, expect } = require(‘@playwright/test’);

test(‘Login form interaction’, async ({ page }) => {

    await page.goto(‘https://www.saucedemo.com/’);

    await page.getByPlaceholder(‘Username’)

        .fill(‘standard_user’);

    await page.getByPlaceholder(‘Password’)

        .fill(‘secret_sauce’);

    await page.getByRole(‘button’, {

        name: ‘Login’

    }).click();

    await expect(page).toHaveURL(/inventory/);

    await expect(

        page.getByText(‘Products’)

    ).toBeVisible();

});

Expected result: The user logs in and reaches the product inventory page.

Use test credentials only on the designated demo application. Never commit real passwords or production credentials to source control.

Example 5: Handle dropdowns and checkboxes

const { test, expect } = require(‘@playwright/test’);

test(‘Dropdown and checkbox example’, async ({ page }) => {

    await page.goto(‘https://testautomationpractice.blogspot.com/’);

    const country = page.locator(‘#country’);

    await country.selectOption({

        label: ‘India’

    });

    await expect(country).toHaveValue(‘india’);

    const checkbox = page.locator(‘#sunday’);

    await checkbox.check();

    await expect(checkbox).toBeChecked();

});

Explanation:

  • selectOption() selects an option from a dropdown.
  • check() selects a checkbox.
  • uncheck() clears a checkbox.
  • toBeChecked() verifies the selected state.

The selectors and expected values must match the current HTML of the target demo page.

Example 6: Handle JavaScript alerts

Playwright supports JavaScript dialog handling, including alerts, confirmations, and prompts.

const { test, expect } = require(‘@playwright/test’);

test(‘Handle alert dialog’, async ({ page }) => {

    await page.goto(‘https://testautomationpractice.blogspot.com/’);

    page.once(‘dialog’, async dialog => {

        console.log(‘Alert message:’, dialog.message());

        await dialog.accept();

    });

    await page.getByRole(‘button’, {

        name: ‘Alert’

    }).click();

});

Expected result: Playwright captures the alert message and accepts the dialog.

Register the dialog handler before clicking the button to avoid missing the event.

6. Browser Tabs, Frames, Contexts, and Screenshots

These are important Playwright JavaScript examples for real-world browser automation.

Example 7: Handle multiple tabs

const { test, expect } = require(‘@playwright/test’);

test(‘Handle new browser tab’, async ({ page }) => {

    await page.goto(‘https://playwright.dev/’);

    const newPagePromise = page.waitForEvent(‘popup’);

    await page.getByRole(‘link’, {

        name: ‘GitHub’

    }).click();

    const newPage = await newPagePromise;

    await newPage.waitForLoadState();

    console.log(‘New tab URL:’, newPage.url());

    await expect(newPage).toHaveURL(/github\.com/);

});

A popup is a new page opened by the current page. Waiting for the popup event before clicking prevents timing issues.

Example 8: Work with frames

const { test, expect } = require(‘@playwright/test’);

test(‘Handle iframe’, async ({ page }) => {

    await page.goto(‘YOUR_TEST_PAGE_URL’);

    const frame = page.frameLocator(‘#iframe1’);

    await frame.getByRole(‘button’, {

        name: ‘Submit’

    }).click();

});

Replace the URL and iframe selector with values from your application.

frameLocator() makes it easier to locate and interact with elements inside an iframe.

Example 9: Capture screenshots

const { test } = require(‘@playwright/test’);

test(‘Capture webpage screenshot’, async ({ page }) => {

    await page.goto(‘https://playwright.dev/’);

    await page.screenshot({

        path: ‘screenshots/homepage.png’,

        fullPage: true

    });

});

Create the screenshots directory before running this standalone example.

Screenshots are useful for visual debugging, defect evidence, and regression testing.

7. Playwright Assertions and Auto-Waiting

Assertions verify whether an application behaves as expected.

One important advantage of Playwright is its auto-retrying web-first assertions. Instead of checking an element only once, Playwright retries until the expected condition is satisfied or the assertion timeout is reached.

Playwright+1

Example 10: Validate page title and element visibility

const { test, expect } = require(‘@playwright/test’);

test(‘Validate page elements’, async ({ page }) => {

    await page.goto(‘https://playwright.dev/’);

    await expect(page).toHaveTitle(/Playwright/);

    await expect(

        page.getByRole(‘link’, {

            name: ‘Get started’

        })

    ).toBeVisible();

    await expect(page).toHaveURL(/playwright\.dev/);

});

Common assertions include:

  • toBeVisible()
  • toBeHidden()
  • toHaveText()
  • toContainText()
  • toHaveValue()
  • toBeEnabled()
  • toBeChecked()
  • toHaveURL()
  • toHaveTitle()

Avoid unnecessary waitForTimeout() calls. Use locator actions and web-first assertions instead. They make automation scripts more reliable.

Playwright

8. Build a Real-World Login and Search Testing Project

Individual scripts are useful for learning, but professional QA projects require connected test cases and reusable code.

Let’s organize the examples into a small automation framework.

Recommended project structure

playwright-js-examples/

│

├── tests/

│   ├── login.spec.js

│   ├── search.spec.js

│   └── form.spec.js

│

├── pages/

│   ├── LoginPage.js

│   └── SearchPage.js

│

├── test-data/

│   └── users.json

│

├── playwright.config.js

└── package.json

Example 11: Data-driven login testing

Create test-data/users.json:

[

  {

    “username”: “tomsmith”,

    “password”: “SuperSecretPassword!”,

    “expected”: “success”

  },

  {

    “username”: “invaliduser”,

    “password”: “wrongpassword”,

    “expected”: “failure”

  }

]

Create tests/login.spec.js:

const { test, expect } = require(‘@playwright/test’);

const users = require(‘../test-data/users.json’);

for (const user of users) {

    test(`Login test: ${user.expected}`, async ({ page }) => {

        await page.goto(‘https://the-internet.herokuapp.com/login’);

        await page.locator(‘#username’).fill(user.username);

        await page.locator(‘#password’).fill(user.password);

        await page.getByRole(‘button’, {

            name: ‘Login’

        }).click();

        const message = page.locator(‘#flash’);

        if (user.expected === ‘success’) {

            await expect(message).toContainText(

                ‘You logged into a secure area!’

            );

        } else {

            await expect(message).toContainText(

                ‘Your username is invalid!’

            );

        }

    });

}

Why is this useful?

The same test logic executes with multiple input combinations. This approach is useful for positive testing, negative testing, and regression testing.

Example 12: Search functionality testing

const { test, expect } = require(‘@playwright/test’);

test(‘Verify website search’, async ({ page }) => {

    await page.goto(‘https://playwright.dev/’);

    await page.getByRole(‘button’, {

        name: ‘Search’

    }).click();

    await page.getByPlaceholder(‘Search docs’)

        .fill(‘locators’);

    await expect(

        page.getByText(/locators/i).first()

    ).toBeVisible();

});

The example demonstrates the search workflow. Because website search interfaces can change, verify the current search button and placeholder against the live application before using this test.

9. Page Object Model with Playwright JavaScript

Page Object Model (POM) is a design pattern used to separate page interactions from test cases.

It improves code reusability, readability, and maintenance.

Example 13: Create a LoginPage class

Create pages/LoginPage.js:

class LoginPage {

    constructor(page) {

        this.page = page;

        this.username = page.locator(‘#username’);

        this.password = page.locator(‘#password’);

        this.loginButton = page.locator(‘button[type=”submit”]’);

        this.message = page.locator(‘#flash’);

    }

    async open() {

        await this.page.goto(

            ‘https://the-internet.herokuapp.com/login’

        );

    }

    async login(username, password) {

        await this.username.fill(username);

        await this.password.fill(password);

        await this.loginButton.click();

    }

}

module.exports = LoginPage;

Create tests/login-pom.spec.js:

const { test, expect } = require(‘@playwright/test’);

const LoginPage = require(‘../pages/LoginPage’);

test(‘Login using Page Object Model‘, async ({ page }) => {

    const loginPage = new LoginPage(page);

    await loginPage.open();

    await loginPage.login(

        ‘tomsmith’,

        ‘SuperSecretPassword!’

    );

    await expect(loginPage.message).toContainText(

        ‘You logged into a secure area!’

    );

});

Benefits of POM:

  • Reduces duplicate code.
  • Makes test cases easier to understand.
  • Simplifies maintenance when UI elements change.
  • Supports reusable automation components.
  • Helps build scalable enterprise test frameworks.

For a deeper architectural explanation, internally link this section to your Playwright Framework Design pillar article and Playwright JavaScript Page Object Model cluster article.

10. Playwright API Testing and Response Validation

Playwright also supports API testing without opening a browser.

The request fixture allows you to send HTTP requests and validate responses.

Example 14: GET API request

const { test, expect } = require(‘@playwright/test’);

test(‘Verify GET API response’, async ({ request }) => {

    const response = await request.get(

        ‘https://jsonplaceholder.typicode.com/posts/1’

    );

    expect(response.status()).toBe(200);

    const data = await response.json();

    expect(data.id).toBe(1);

    expect(data).toHaveProperty(‘title’);

    console.log(data);

});

Expected result: The API returns HTTP 200, and the response contains the expected post information.

Example 15: POST API request

const { test, expect } = require(‘@playwright/test’);

test(‘Create a new post’, async ({ request }) => {

    const response = await request.post(

        ‘https://jsonplaceholder.typicode.com/posts’,

        {

            data: {

                title: ‘Playwright Testing,

                body: ‘Learning API automation,

                userId: 1

            }

        }

    );

    expect(response.status()).toBe(201);

    const result = await response.json();

    expect(result.title).toBe(‘Playwright Testing’);

    expect(result.userId).toBe(1);

});

These examples use JSONPlaceholder, a public testing API. It simulates API operations and should not be treated as a production database.

API testing is useful for validating backend functionality, response codes, JSON data, and application integrations.

11. Playwright Configuration, Debugging, and Reporting

A good test framework needs centralized configuration.

Create playwright.config.js:

const { defineConfig } = require(‘@playwright/test’);

module.exports = defineConfig({

    testDir: ‘./tests’,

    fullyParallel: true,

    retries: 1,

    reporter: [

        [‘list’],

        [‘html’, { open: ‘never’ }]

    ],

    use: {

        headless: true,

        screenshot: ‘only-on-failure’,

        trace: ‘retain-on-failure’

    },

    projects: [

        {

            name: ‘chromium’,

            use: { browserName: ‘chromium’ }

        },

        {

            name: ‘firefox’,

            use: { browserName: ‘firefox’ }

        },

        {

            name: ‘webkit’,

            use: { browserName: ‘webkit’ }

        }

    ]

});

This configuration enables three browser projects, parallel testing, retries, screenshots on failure, and HTML reporting.

Useful execution commands

CommandPurpose
npx playwright testRun all tests
npx playwright test –headedRun with visible browser
npx playwright test –project=chromiumRun Chromium tests
npx playwright test tests/login.spec.jsRun one test file
npx playwright test –debugDebug tests
npx playwright test –uiOpen UI mode
npx playwright show-reportView HTML report

Playwright provides an HTML reporter and debugging tools such as UI Mode, Inspector, and traces.

Playwright+1

CI/CD integration using GitHub Actions

Create .github/workflows/playwright.yml:

name: Playwright JavaScript Tests

on:

  push:

  pull_request:

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – uses: actions/checkout@v4

      – uses: actions/setup-node@v4

        with:

          node-version: 22

      – name: Install dependencies

        run: npm ci

      – name: Install browsers

        run: npx playwright install –with-deps

      – name: Execute tests

        run: npx playwright test

      – name: Upload report

        if: always()

        uses: actions/upload-artifact@v4

        with:

          name: playwright-report

          path: playwright-report/

This workflow executes automation tests whenever code is pushed or a pull request is created. It also preserves the HTML report as a downloadable CI artifact.

12. Common Mistakes in Playwright JavaScript Automation

Beginners often make mistakes when writing browser automation scripts. Understanding these problems helps build reliable test frameworks.

Common mistakeRecommended solution
Using fixed waitsUse auto-waiting and web-first assertions
Using unstable CSS selectorsPrefer role, label, and test ID locators
Repeating browser setupUse Playwright fixtures
Hardcoding credentialsUse environment variables
Ignoring failed test evidenceEnable screenshots and traces
Writing everything in one fileFollow Page Object Model
Testing only in ChromeConfigure Chromium, Firefox, and WebKit
Ignoring API testingInclude backend validation

How to troubleshoot failed tests

  1. Run the failed test using –debug.
  2. Check the locator and element visibility.
  3. Inspect the browser console and network requests.
  4. Review the screenshot and trace.
  5. Verify whether the application or test data has changed.
  6. Re-run the test after fixing the root cause.

13. Best Practices for Playwright JavaScript Examples

Follow these recommendations when developing professional automation projects:

  1. Use reusable components: Create page classes for common application operations.
  2. Choose reliable locators: Prefer user-facing locators over fragile XPath expressions.
  3. Use assertions: Validate actual application behavior after every important operation.
  4. Organize test data: Maintain separate JSON or other data files.
  5. Implement cross-browser testing: Execute tests against all required browser engines.
  6. Use parallel execution: Reduce regression testing execution time.
  7. Generate reports: Maintain execution reports and failure evidence.
  8. Integrate CI/CD: Execute automated tests whenever application code changes.
  9. Maintain independent tests: Avoid depending on the execution order of test cases.
  10. Protect sensitive information: Never expose passwords, tokens, or production credentials.

These practices help QA engineers develop maintainable frameworks suitable for enterprise automation projects.

Playwright+1

14. Playwright JavaScript Interview Questions and Answers

Here are some common interview questions for freshers and experienced QA Automation Engineers.

Q1. What is Playwright in JavaScript?

Playwright is an open-source browser automation framework that supports Chromium, Firefox, and WebKit. JavaScript developers use it for end-to-end testing, browser automation, and API testing.

Q2. Is Playwright JavaScript suitable for beginners?

Yes. Beginners can start with browser launch, navigation, locators, clicking, form filling, and assertions before learning advanced framework concepts.

Q3. What is the difference between Playwright and Selenium?

Playwright provides built-in auto-waiting, browser contexts, web-first assertions, and modern browser automation APIs. Selenium uses the WebDriver standard and supports a broader ecosystem of browser and language integrations.

Q4. What is the Page Object Model?

POM is a design pattern that separates page-specific locators and actions from test cases. It improves code reusability and maintainability.

Q5. How do you handle multiple browsers?

Use Playwright projects in playwright.config.js to configure Chromium, Firefox, and WebKit.

Q6. What is auto-waiting?

Auto-waiting means Playwright automatically checks whether an element is ready before performing an action. This reduces synchronization problems.

Q7. Can Playwright perform API testing?

Yes. Playwright provides an API request fixture for sending GET, POST, PUT, PATCH, and DELETE requests and validating responses.

Q8. How do you generate HTML reports?

Configure the HTML reporter and execute:

npx playwright test

npx playwright show-report

15. Frequently Asked Questions (FAQs)

1. What is Playwright JavaScript examples?

Playwright JavaScript examples are practical automation scripts written in JavaScript to test web applications, interact with browser elements, validate application behavior, and automate repetitive tasks.

2. How do I get started with Playwright JavaScript examples?

Follow these steps:

  1. Install Node.js.
  2. Create a JavaScript project.
  3. Install @playwright/test.
  4. Install browser binaries.
  5. Create your first .spec.js file.
  6. Execute tests using npx playwright test.

3. Is Playwright JavaScript examples suitable for beginners?

Yes. The examples can be learned progressively, starting with browser navigation and simple interactions before moving to API testing, POM, and CI/CD.

4. Can we use JavaScript instead of TypeScript in Playwright?

Yes. Playwright supports both JavaScript and TypeScript. JavaScript does not require TypeScript compilation and is suitable for beginners.

5. Can Playwright automate Chrome?

Yes. Playwright supports Chromium, which can run in headless or headed mode. It can also connect to supported browser installations using the appropriate launch or connection APIs.

6. What is the difference between Playwright Test and Playwright Library?

Playwright Test is a complete test runner with fixtures, assertions, parallel execution, and reporting.

Playwright Library provides browser automation APIs without the built-in Playwright Test runner. It is useful for standalone scripts and custom automation workflows.

Playwright

7. Can Playwright be used for regression testing?

Yes. Playwright can execute a collection of automated test cases repeatedly to validate that existing application functionality continues working after code changes.

8. Is Playwright free to use?

Yes. Playwright is an open-source framework available under the Apache 2.0 license.

Leave a Comment

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