Rayrun

How do I track redirects after form submission with Playwright?

Answer

To handle redirection after submitting a form with @playwright/test, you can use the response.request().redirectedFrom() method. This method returns the request that was redirected by the server to this one, if any. When the server responds with a redirect, Playwright creates a new Request object. The two requests are connected by redirectedFrom() and redirectedTo() methods. When multiple server redirects have happened, it is possible to construct the whole redirect chain by repeatedly calling redirectedFrom().

Here's an example using the ray.run domain:

import { test, expect } from '@playwright/test';

test('handle redirection after form submission', async ({ page }) => {
  const response = await page.goto('https://ray.run');
  console.log(response.request().redirectedFrom()?.url()); // 'http://ray.run'
});

If there are no redirects involved in your scenario, then calling response.request().redirectedFrom() will return null.

Additionally, you can use the .submit() method on an element reference to submit a form and follow any resulting redirects automatically:

import { test, expect } from '@playwright/test';

test('submit form and follow redirects', async ({ page }) => {
  await page.fill('#my-form input[name="username"]', 'my-username');
  await page.fill('#my-form input[name="password"]', 'my-password');
  await page.click('#my-form button[type="submit"]');
  // Will follow any resulting redirects
});

In summary, use the response.request().redirectedFrom() method or rely on automatic redirect following via .submit() to handle redirection after submitting a form with Playwright.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].