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
page.goto(url)
β navigates to a given URL.
page.goBack()
β simulates clicking the browser Back button.
page.goForward()
β simulates clicking the browser Forward button.
page.reload()
β reloads the current page.
Assertions (toHaveURL
, toHaveTitle
) β verify correct navigation.
Behind the Scenes
- When you run
page.goto()
, Playwright waits for the page to finish loading before moving forward. - When using
page.goBack()
andpage.goForward()
, Playwright works with the browserβs history stack β exactly like when you press back/forward in Chrome/Firefox. page.reload()
clears the page state and reloads everything from the server.- The
expect
assertions confirm that navigation was successful and correct.
What Youβll See
1. Browser opens and loads π https://vinothqaacademy.com/demo-site/
2. Browser navigates to π https://vinothqaacademy.com/
3. Browser goes back π returns to demo-site
page
Test asserts URL matches the expected demo-site
URL.
4. Browser goes forward π returns to vinothqaacademy.com
homepage
Test asserts URL matches the homepage.
5. Browser reloads the page
Page refreshes and the title is validated with regex (Vinoth QA Academy
).