Skip to content
CodeKruPro

Use goBack() and goForward()

3/70

Use goBack() and goForward()

Playwright can simulate browser history navigation:

  • page.goBack() — goes to the previous page
  • page.goForward() — goes to the next page

Task:

  1. Navigate to https://testkru.com/Elements/TextFields
  2. Navigate to https://testkru.com/Elements/Buttons
  3. Go back and print the title
  4. Go forward and print the title

Expected output:

After back: Text Fields
After forward: Buttons

About this lesson

Browser history in Playwright: goBack(), goForward() and reload()

Learn Playwright JSBeginnerGetting Started

How it works

page.goBack() and page.goForward() move through the history of the current tab, and page.reload() loads the same address again. All three wait for the new page to load, accept the same waitUntil option as goto(), and return the main response.

There is one twist. When there is no page to go back or forward to, the method resolves to null instead of throwing. It also returns null for history entries that only change the URL hash, because no new document is loaded.

About the assignment

Two navigations are already done for you, Text Fields and then Buttons, so the tab has a short history. The task is to step back to the first page and forward to the second, logging the title each time.

What you will do

  1. Await page.goBack(), then log the title after the label After back:.
  2. Await page.goForward(), then log the title after the label After forward:.
  3. Await page.title() after each move so the title belongs to the page you reached.
  4. Keep browser.close() as the final line.

Common mistakes

  • Treating null as success

    Code such as (await page.goBack()).status() throws a TypeError when the result is null. Check the value before using it.

  • Keeping old element handles

    An ElementHandle from before the navigation points at a destroyed page. Locators avoid this because they look the element up again each time.

  • Asserting too early in single page apps

    Client-side routers can update the view after the history change. Wait with await expect(page).toHaveURL(...), which retries, instead of reading page.url() once.

In a real test suite

History calls help test flows that real users break by pressing Back: multi-step forms, filtered product lists, and apps that store state in the URL. expect(page).toHaveURL() is the usual assertion after each step.

Starter code

The editor above opens with this code. Fill in the TODO lines, then run and submit it.

main.js
const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();

    await page.goto('https://testkru.com/Elements/TextFields');
    await page.goto('https://testkru.com/Elements/Buttons');

    // TODO: Go back and print title
    // TODO: Go forward and print title

    await browser.close();
})();