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
- Await
page.goBack(), then log the title after the labelAfter back:. - Await
page.goForward(), then log the title after the labelAfter forward:. - Await
page.title()after each move so the title belongs to the page you reached. - 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 isnull. Check the value before using it.Keeping old element handles
An
ElementHandlefrom 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 readingpage.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.
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();
})();