Tuesday, April 29, 2025

Understanding navigation in playwright

When building reliable end-to-end tests, one of the most critical skills is controlling and monitoring navigation, that moment when a page loads, reloads, or redirects. With Playwright, Microsoft’s powerful browser automation library, navigating like a pro is not only possible. it's intuitive.

In this post, we'll explore how to handle navigations in Playwright, including direct URL changes, link clicks, popups, and iframes. Whether you're testing traditional web apps or dynamic SPAs, this guide will help you stay in sync with what your users experience.

Understanding navigation in playwright


Playwright can navigate to URLs and handle navigations caused by the page interactions.


Basic navigation

Simplest form of a navigation is opening a URL:

// Navigate the page
await page.goto('https://example.com');
The code above loads the page and waits for the web page to fire the load event. The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets, scripts, iframes, and images.


When is the page loaded?

Modern pages perform numerous activities after the load event was fired. They fetch data lazily, populate UI, load expensive resources, scripts and styles after the load event was fired. There is no way to tell that the page is loaded, it depends on the page, framework, etc. So when can you start interacting with it?

In Playwright you can interact with the page at any moment. It will automatically wait for the target elements to become actionable.

// Navigate and click element
// Click will auto-wait for the element
await page.goto('https://example.com');
await page.getByText('Example Domain').click();

Waiting for navigation

Clicking an element could trigger multiple navigations. In these cases, it is recommended to explicitly page.waitForURL() to a specific url.

await page.getByText('Click me').click();
await page.waitForURL('**/login');

Navigation is one of the most essential pieces of a stable Playwright test.


No comments:

Post a Comment