Handle Browser Navigation
In this example, we will learn how to handle back, forward, and reload browser actions using Playwright.
Code Example
import { test, expect } from '@playwright/test';
test('Handle Browser Navigation', async ({ page }) => {
// Step 1: Navigate to first page
await page.goto('https://vinothqaacademy.com/demo-site/');
// Step 2: Navigate to another page
await page.goto('https://vinothqaacademy.com/');
// Step 3: Go back to the previous page
await page.goBack();
await expect(page).toHaveURL('https://vinothqaacademy.com/demo-site/'); // Assertion
// Step 4: Go forward to the next page
await page.goForward();
await expect(page).toHaveURL('https://vinothqaacademy.com/'); // Assertion
// Step 5: Reload the current page
await page.reload();
await expect(page).toHaveTitle(/Vinoth QA Academy/); // Regex validation for flexibility
});
Explanation
- import { test } from '@playwright/test'
→ imports Playwright’s built-in test runner.
– test('Launch Application', async ({ page }) => { ... })
→ defines a test case with the name Launch Application.
– page.goto(URL)
→ opens the browser and navigates to the given application URL.
– page.waitForTimeout(3000)
→ makes the browser wait for 3 seconds (just for demo purposes).
– Browser context and page auto-close after the test run, no need to close manually.
Behind the Scenes
– Playwright automatically launches a browser context for each test.
– All Playwright functions are asynchronous, which is why we use async/await
to run steps in order.
– waitForTimeout()
is used here only for demo. In real automation, prefer auto-waiting or waitForSelector()
for stability.
What You’ll See
– A browser window opens.
– The demo site loads.
– The page stays open for 3 seconds.
– The browser closes automatically.
Try It Yourself
– Change the URL to https://playwright.dev/
and rerun the test.
– Modify the timeout value (e.g., 1000
ms = 1 second).
– Remove waitForTimeout()
and notice how quickly the test finishes