如何在Playwright中获取当前上下文?以及TypeScript环境下使用Playwright在新标签页打开URL时如何获取当前上下文(附C#实现示例)
Hey there! Let's tackle your two Playwright TypeScript questions based on your C# code example.
1. 获取当前上下文
In TypeScript, there are two straightforward ways to get the current BrowserContext:
From an existing Page instance: Every
Pageobject has acontext()method that returns its associatedBrowserContext. This is perfect if you already have access to a page in your code:// Assuming you have a Page instance (e.g., from context.newPage()) const currentContext = page.context();Directly reference the context when creating it: When you initialize a context from a Browser, just store the reference for later use. This is ideal if you need to manage the context across multiple functions:
import { chromium } from '@playwright/test'; const browser = await chromium.launch(); // Save this context reference to use anywhere in your code const currentContext = await browser.newContext(); const page = await currentContext.newPage();
2. TypeScript实现新标签页打开URL(对应你的C#代码)
Here's the TypeScript equivalent of your C# method, using Playwright's native APIs. We'll use context.waitForPage() to handle the new tab creation, just like your RunAndWaitForPageAsync call:
import { Page } from '@playwright/test'; async function openUrlInNewTab(page: Page, url: string): Promise<number> { const context = page.context(); // Wait for the new page to be created while triggering window.open const newPage = await context.waitForPage(async () => { await page.evaluate((targetUrl) => window.open(targetUrl), url); }); // Wait for the new page to finish loading await newPage.waitForLoadState(); // Return the index of the new page (same logic as your C# code) return context.pages().length - 1; }
代码解释:
context.waitForPage()listens for a new page to be created in the context, and we trigger the creation by runningwindow.open()viapage.evaluate().page.evaluate()is the TypeScript equivalent of yourExecuteJavaScriptmethod—it runs the provided JS code in the browser context, passing the URL as an argument.- After the new page loads, we return the index of the last page in the context (since the new tab is the most recent one added).
内容的提问来源于stack exchange,提问作者Greg Finzer

