Rayrun

How do I switch between browser contexts in Playwright without losing the previous step?

Answer

To run two actions synchronously in an async function without losing the previous step when Playwright switches between browser contexts, use the withContext method. This allows you to switch between different browser contexts and execute code within each context.

Here's how you can do it:

  1. Create a new context: Use the browser.newContext() method to create a new browser context.

    const ctx = await page.context().newContext();
  2. Perform actions in the new context: Use Playwright action methods like page.goto(), page.click(), etc., within the new context.

    await ctx.page.goto('https://ray.run');
  3. Close the new context: Once you've completed your actions within the new context, close it using the .close() method.

    await ctx.close();
  4. Switch back to the original context: Use the withContext method to switch back to your original context and continue with your remaining actions. The withContext method takes a callback function as its argument, which contains all the remaining code that needs to be executed in the original context.

    await page.withContext(async () => {
      await page.click('#button');
    });

Here's a complete example using @playwright/test:

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

test('run two actions synchronously', async ({ page }) => {
  // Perform first action in original context
  await page.goto('https://ray.run');

  // Create a new browser context
  const ctx = await page.context().newContext();

  // Perform second action in new browser context
  await ctx.page.goto('https://ray.run/blog');

  // Close the new browser context
  await ctx.close();

  // Switch back to original browser context and perform third action
  await page.withContext(async () => {
    await page.click('#button');
  });
});

In this example, we first navigate to "ray.run" in our original browser context, create a new context, and navigate to "ray.run/blog" within the new context. After closing the new context, we switch back to the original context using withContext and click on a button with ID "button".

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].