To switch to a new window in Playwright, use the context.waitForEvent('page')
method. This method waits for a new popup window to appear and returns a promise that resolves to the page object of the new window. You can then interact with the new window as you would with any other page.
Here's a code snippet demonstrating how to switch to a new window:
import { test } from '@playwright/test';
test('Switch to new window', async ({ context, page }) => {
const [newPage] = await Promise.all([
context.waitForEvent('page'),
page.click('#my-link-that-opens-a-new-window')
]);
// Grant permissions and bring focus to the new page
await context.grantPermissions(newPage, ['clipboard-read', 'clipboard-write']);
await newPage.bringToFront();
// Interact with the new page
await newPage.goto('https://ray.run');
});
In this example, we use context.waitForEvent('page')
instead of page.waitForEvent('popup')
because when a link opens in a new tab or window, Playwright creates a new browser context for that tab or window. So, we need to wait for an event on the browser context level instead of on the individual page level.
Once you have the newPage
object, use the context.grantPermissions()
and newPage.bringToFront()
methods to grant permissions and bring focus to the new window, respectively. Now you can interact with the new window in your Playwright tests.
If you still have questions, please ask a question and I will try to answer it.
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].