Greg Finzer
Greg Finzer

Reputation: 7054

How to get the current context in Playwright?

I have a need to open a URL in a new tab. How do I get the current context of Playwright in TypeScript? Here is what I have for C#:

public async Task<int> OpenUrlInNewTab(string url)
{
    var newPage = await _context.RunAndWaitForPageAsync(async () =>
    {
        await ExecuteJavaScript("url => window.open(url);", new[] { url });
    });
    await newPage.WaitForLoadStateAsync();
    return _context.Pages.Count - 1;
}

public async Task<object> ExecuteJavaScript(string javaScript, object? arg = null)
{
    return await _page.EvaluateAsync<object>(javaScript, arg);
}

Upvotes: 1

Views: 5882

Answers (1)

ttqa
ttqa

Reputation: 602

To get the context of a new tab that has opened from your application in Playwright, you need to use browserContext.on('page')

Official docs: https://playwright.dev/docs/api/class-browsercontext#browser-context-event-page

Here is an example were clicking a button "Ok" will open a new tab and we want to continue the test in the new tab:

        /*  When "Ok" is clicked the test waits for a new page event and assigns to new page object to a variable called newPage
            After this point we want the test to continue in the new tab,
            so we'll have to use the newly defined newPage variable when working on that tab
        */
        const [newPage] = await Promise.all([
            context.waitForEvent('page'),
            page.locator("span >> text=Ok").click()
            
        ])
        await newPage.waitForLoadState();

        console.log("New page has opened and its url is: " + newPage.url());

        // We are working on a new tab now thus calling newPage instead of page
        await newPage.locator("#description").type("We got this!");

Notice how we access the initial page with "page.locator" and the new page with "newPage.locator" once we have defined it.

Upvotes: 1

Related Questions