Rayrun

How can I open multiple pages in the same browser window using Playwright's JavaScript/TypeScript API?

Answer

Opening Multiple Pages in the Same Browser Window

First, you'll need to create a new browser context. This creates a separate environment for your pages to run in.

const { chromium } = require('@playwright/test');

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
})();

Next, create multiple pages within the same context. Each page represents a separate tab or popup window within the browser.

const pageOne = await context.newPage();
const pageTwo = await context.newPage();

You can navigate to different URLs and interact with each page individually.

await pageOne.goto('https://ray.run');
await pageTwo.goto('https://ray.run/blog');

To handle new pages that are opened by links with target="_blank", use the waitForEvent() method on your context object.

const newPagePromise = context.waitForEvent('page');
await pageOne.click('a[target="_blank"]');
const newPage = await newPagePromise;

Ensure that all pages are loaded before performing any actions. You can use methods like waitForLoadState() or check for specific elements on each page.

await Promise.all([
  pageOne.waitForLoadState(),
]);

By following these steps, you can have multiple pages with different contexts open in the same browser window and perform actions on them individually. Remember to handle any errors or exceptions that may occur during the execution of your code.

References

Thank you!
Was this helpful?
Still have questions?

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

Related Discord Threads

Related Questions

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